Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,28 +1,26 @@
# [363.Max Sum of Rectangle No Larger Than K][title]

> [!WARNING|style:flat]
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)

## Description
Given an `m x n` matrix `matrix` and an integer `k`, return the max sum of a rectangle in the matrix such that its sum is no larger than `k`.

It is **guaranteed** that there will be a rectangle with a sum no larger than `k`.

**Example 1:**

**Example 1:**
![example1](./sum-grid.jpeg)

```
Input: a = "11", b = "1"
Output: "100"
Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: Because the sum of the blue rectangle [[0, 1], [-2, 3]] is 2, and 2 is the max number no larger than k (k = 2).
```

## 题意
> ...
**Example 2:**

## 题解

### 思路1
> ...
Max Sum of Rectangle No Larger Than K
```go
```

Input: matrix = [[2,2,-1]], k = 3
Output: 3
```

## 结语

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,33 @@
package Solution

func Solution(x bool) bool {
return x
func Solution(matrix [][]int, k int) int {
rows, cols := len(matrix), len(matrix[0])
cache := make([][]int, rows+1)
for i := 0; i <= rows; i++ {
cache[i] = make([]int, cols+1)
}
for r := rows - 1; r >= 0; r-- {
for c := cols - 1; c >= 0; c-- {
cache[r][c] = matrix[r][c] + cache[r+1][c] + cache[r][c+1] - cache[r+1][c+1]
}
}
first := true
ans := 0
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
for re := r; re < rows; re++ {
for rc := c; rc < cols; rc++ {
x := cache[r][c] - cache[re+1][c] - cache[r][rc+1] + cache[re+1][rc+1]
if x <= k {
if first || x > ans {
ans = x
first = false
}
}
}

}
}
}
return ans
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,20 @@ func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs bool
expect bool
inputs [][]int
k int
expect int
}{
{"TestCase", true, true},
{"TestCase", true, true},
{"TestCase", false, false},
{"TestCase1", [][]int{
{1, 0, 1}, {0, -2, 3},
}, 2, 2},
{"TestCase2", [][]int{{2, 2, -1}}, 3, 3},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
got := Solution(c.inputs, c.k)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
Expand All @@ -30,10 +32,10 @@ func TestSolution(t *testing.T) {
}
}

//压力测试
// 压力测试
func BenchmarkSolution(b *testing.B) {
}

//使用案列
// 使用案列
func ExampleSolution() {
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.