01 matrix leetcode java

vuongtrieu166

New member
## 01 Ma trận LeetCode Java

[Hashtags]:

### Vấn đề

Đưa ra một ma trận 2D của các số nguyên `A`, hãy tìm tổng số tối đa của bất kỳ ** Subrectangle nào **.

** Liên kết trục ** có nghĩa là Subrectangle phải có cùng chiều rộng và chiều cao.

**Ví dụ 1:**

`` `
Đầu vào: [[1,2,3], [4,5,6], [7,8,9]]]]
Đầu ra: 20
Giải trình:
Tổng tối đa là 20, là tổng của hình chữ nhật `[1,2,3], [4,5,6]`.
`` `

### Giải pháp

`` `java
Giải pháp lớp {
công khai int maxsubmatrix (int [] [] a) {
int m = a.length, n = a [0] .length;
int [] dp = new int [n + 1];
int ans = integer.min_value;
for (int i = 0; i <m; i ++) {
for (int j = 0; j <n; j ++) {
dp [j + 1] = dp [j] + a [j];
ANS = Math.Max (ANS, DP [J + 1]);
for (int k = j+1; k <n; k ++) {
dp [k + 1] = math.max (dp [k + 1], dp [k] - a [j]);
ANS = MATH.MAX (ANS, DP [K + 1]);
}
}
}
trả lại ans;
}
}
`` `

### Giải trình

Chúng ta có thể sử dụng một mảng tổng tiền tố để tính tổng của mỗi subarray.Sau đó, chúng ta có thể lặp lại tất cả các subrectangles có thể và tìm tổng số tiền tối đa.

Độ phức tạp thời gian của giải pháp này là O (Mn^2).

### Người giới thiệu

* [Sự cố LeetCode 84: Submatrix lớn nhất] (https://leetcode.com/problems/largest-submatrix/)
=======================================
## 01 Matrix Leetcode Java

[Hashtags]: #matrix #leetcode #Java #datastructure #algorithm

### Problem

Given a 2D matrix of integers `A`, find the maximum sum of any **axis-aligned** subrectangle.

**Axis-aligned** means that the subrectangle must have the same width and height.

**Example 1:**

```
Input: [[1,2,3],[4,5,6],[7,8,9]]
Output: 20
Explanation:
The maximum sum is 20, which is the sum of the rectangle `[1,2,3],[4,5,6]`.
```

### Solution

```java
class Solution {
public int maxSubmatrix(int[][] A) {
int m = A.length, n = A[0].length;
int[] dp = new int[n + 1];
int ans = Integer.MIN_VALUE;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
dp[j + 1] = dp[j] + A[j];
ans = Math.max(ans, dp[j + 1]);
for (int k = j + 1; k < n; k++) {
dp[k + 1] = Math.max(dp[k + 1], dp[k] - A[j]);
ans = Math.max(ans, dp[k + 1]);
}
}
}
return ans;
}
}
```

### Explanation

We can use a prefix sum array to calculate the sum of each subarray. Then, we can iterate over all possible subrectangles and find the maximum sum.

The time complexity of this solution is O(mn^2).

### References

* [LeetCode Problem 84: Largest Submatrix](https://leetcode.com/problems/largest-submatrix/)
 
Join ToolsKiemTrieuDoGroup
Back
Top
AdBlock Detected

We get it, advertisements are annoying!

Sure, ad-blocking software does a great job at blocking ads, but it also blocks useful features of our website. For the best site experience please disable your AdBlocker.

I've Disabled AdBlock