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
}
相关推荐
愚润求学11 小时前
【动态规划】01背包问题
c++·算法·leetcode·动态规划
dying_man14 小时前
LeetCode--44.通配符匹配
算法·leetcode
Paper Clouds14 小时前
代码随想录|图论|15并查集理论基础
数据结构·算法·leetcode·深度优先·图论
GGBondlctrl15 小时前
【leetcode】字符串,链表的进位加法与乘法
算法·leetcode·链表·字符串相加·链表相加·字符串相乘
打野二师兄17 小时前
LeetCode经典题解:21、合并两个有序链表
算法·leetcode·链表
前端拿破轮17 小时前
腾讯面试官:听说你在字节面试用栈实现队列,那怎么用队列实现栈呢?
算法·leetcode·面试
亚洲第一中锋_哈达迪18 小时前
详解缓存淘汰策略:LFU
后端·缓存·golang
nextera-void20 小时前
深入浅出 Golang:一次精神之旅
开发语言·golang·go
胡萝卜的兔1 天前
golang -gorm 增删改查操作,事务操作
开发语言·后端·golang
Y1nhl1 天前
力扣_二叉树的BFS_python版本
python·算法·leetcode·职场和发展·宽度优先