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
}
相关推荐
名字还没想好☜14 小时前
Go 的 time.Ticker 陷阱:定时任务里被忽略的内存泄漏与正确关闭
java·数据库·golang·go·定时器
Navigator_Z18 小时前
LeetCode //C - 1156. Swap For Longest Repeated Character Substring
c语言·算法·leetcode
灯澜忆梦20 小时前
Go 语言 _JSON---序列化与反序列化
开发语言·golang·json
布朗克16821 小时前
Go入门到精通-22-同步原语
开发语言·后端·golang·同步原语
兰令水21 小时前
hot100【acm版】【2026.7.19打卡-java版本】
java·数据结构·算法·leetcode·面试
怒放de生命20101 天前
【web3基础】go-zero使用etcd实现服务注册与发现(四)
golang·web3·etcd·go-zero
灯澜忆梦1 天前
Go语言_文件---文件操作
开发语言·后端·golang
tkevinjd1 天前
力扣72-编辑距离
算法·leetcode·职场和发展
qz5zwangzihan11 天前
题解:Atcoder Beginner Contest abc467 A~D
c++·题解·atcoder·abc467
Wang's Blog1 天前
Go-Zero项目开发4: 用户服务搜索、详情与统一错误处理
开发语言·golang