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
}
相关推荐
Wy_编程3 小时前
go中的协程Goroutine
开发语言·golang
会编程的土豆4 小时前
Go 语言中的 `new` 关键字(创建指针)
java·算法·golang
x_yeyue4 小时前
2026第十七届蓝桥杯c++B组省赛题解
笔记·算法·蓝桥杯·acm·题解
老四啊laosi5 小时前
[滑动窗口] 12. 将 x 减到 0 的最小操作数
算法·leetcode·将 x 减到 0 的最小操作数
喵了几个咪5 小时前
Kratos 生态双定时器中间件:高精度 hptimer 与标准 cron 选型与实践
微服务·中间件·架构·golang·kratos
Achou.Wang7 小时前
Concurrency patterns - Go 并发模式
开发语言·后端·golang
存在morning7 小时前
【GO语言开发实践】三 GO 工程化快速上手
开发语言·后端·golang
人道领域7 小时前
【LeetCode刷题日记】513.二叉树左下角值的三种解法:从常规BFS到DFS的优雅之旅
数据结构·算法·leetcode·深度优先·广度优先
Achou.Wang7 小时前
Go语言并发编程中的死锁防范与破解之道
服务器·开发语言·golang
子安柠7 小时前
深入理解 Go 反射:原理、实践与性能陷阱
开发语言·golang