Golang | Leetcode Golang题解之第363题矩形区域不超过K的最大数值和

题目:

题解:

Go 复制代码
import "math/rand"

type node struct {
    ch       [2]*node
    priority int
    val      int
}

func (o *node) cmp(b int) int {
    switch {
    case b < o.val:
        return 0
    case b > o.val:
        return 1
    default:
        return -1
    }
}

func (o *node) rotate(d int) *node {
    x := o.ch[d^1]
    o.ch[d^1] = x.ch[d]
    x.ch[d] = o
    return x
}

type treap struct {
    root *node
}

func (t *treap) _put(o *node, val int) *node {
    if o == nil {
        return &node{priority: rand.Int(), val: val}
    }
    if d := o.cmp(val); d >= 0 {
        o.ch[d] = t._put(o.ch[d], val)
        if o.ch[d].priority > o.priority {
            o = o.rotate(d ^ 1)
        }
    }
    return o
}

func (t *treap) put(val int) {
    t.root = t._put(t.root, val)
}

func (t *treap) lowerBound(val int) (lb *node) {
    for o := t.root; o != nil; {
        switch c := o.cmp(val); {
        case c == 0:
            lb = o
            o = o.ch[0]
        case c > 0:
            o = o.ch[1]
        default:
            return o
        }
    }
    return
}

func maxSumSubmatrix(matrix [][]int, k int) int {
    ans := math.MinInt64
    for i := range matrix { // 枚举上边界
        sum := make([]int, len(matrix[0]))
        for _, row := range matrix[i:] { // 枚举下边界
            for c, v := range row {
                sum[c] += v // 更新每列的元素和
            }
            t := &treap{}
            t.put(0)
            s := 0
            for _, v := range sum {
                s += v
                if lb := t.lowerBound(s - k); lb != nil {
                    ans = max(ans, s-lb.val)
                }
                t.put(s)
            }
        }
    }
    return ans
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
相关推荐
Davis_12191 小时前
代码随想录算法训练营27天 | 56. 合并区间、738.单调递增的数字、968.监控二叉树(提高)
数据结构·c++·算法·leetcode·贪心算法
农场主John4 小时前
(栈)Leetcode155最小栈+739每日温度
windows·python·算法·leetcode·
杜子不疼.6 小时前
【LeetCode 415】—字符串相加算法详解
算法·leetcode·职场和发展
仙俊红6 小时前
LeetCode每日一题,2025-08-21
算法·leetcode·职场和发展
一起努力啊~8 小时前
算法题打卡力扣第34题:在排序数组中查找元素的第一个和最后一个位置(mid)
数据结构·算法·leetcode
1白天的黑夜19 小时前
链表-143.重排链表-力扣(LeetCode)
数据结构·leetcode·链表
快去睡觉~16 小时前
力扣73:矩阵置零
算法·leetcode·矩阵
岁忧17 小时前
(nice!!!)(LeetCode 每日一题) 679. 24 点游戏 (深度优先搜索)
java·c++·leetcode·游戏·go·深度优先
小欣加油17 小时前
leetcode 3 无重复字符的最长子串
c++·算法·leetcode
元亓亓亓1 天前
LeetCode热题100--101. 对称二叉树--简单
算法·leetcode·职场和发展