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
}
相关推荐
程序猿练习生1 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
MogulNemenis3 小时前
力扣150题——位运算
数据结构·算法·leetcode
GoppViper8 小时前
golang学习笔记28——golang中实现多态与面向对象
笔记·后端·学习·golang·多态·面向对象
huanxiangcoco9 小时前
55. 跳跃游戏
python·leetcode
Python私教9 小时前
Go语言现代web开发14 协程和管道
开发语言·前端·golang
楚钧艾克9 小时前
Windows系统通过部署wsl + Goland进行跨平台开发
linux·windows·后端·ubuntu·golang
__AtYou__9 小时前
Golang | Leetcode Golang题解之第413题等差数列划分
leetcode·golang·题解
编程点滴9 小时前
go单测报错 monkey undefined jmpToFunctionValue
开发语言·后端·golang
DdddJMs__13511 小时前
C语言 | Leetcode C语言题解之第413题等差数列划分
c语言·leetcode·题解
QXH20000012 小时前
Leetcode—环形链表||
c语言·数据结构·算法·leetcode·链表