#BS0000489. Tổng hình chữ nhật lớn nhất không vượt quá K (Max Sum of Rectangle No Larger Than K)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Tổng hình chữ nhật lớn nhất không vượt quá K (Max Sum of Rectangle No Larger Than K)
Max Sum of Rectangle No Larger Than K
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
An integer grid has rows and columns, numbered from to and from to , respectively. Cell contains an integer . An integer bound is also given.
A rectangle consists of consecutive rows through and consecutive columns through , where and . It includes all cells in those ranges, including the boundary, and must contain at least one cell. Its sum is the total of the selected cells.
Find the largest sum among rectangles whose sums do not exceed . At least one such rectangle is guaranteed to exist.
Input
- The first line contains three integers : the number of rows, the number of columns, and the upper bound on the sum, respectively.
- Each of the next lines describes one row. The -th of these lines contains exactly integers from left to right.
Output
Print one integer: the largest sum not exceeding of a nonempty rectangle in the grid. The answer may be negative.
Subtasks
- Subtask 1 (20 points): ; ; for every , ; at least one nonempty rectangle has a sum not exceeding .
- Subtask 2 (30 points): ; ; for every , ; at least one nonempty rectangle has a sum not exceeding .
- Subtask 3 (50 points): ; ; for every , ; at least one nonempty rectangle has a sum not exceeding .
Examples
Input 1
2 3 2
1 0 1
0 -2 3
Output 1
2
Explanation 1
The grid has two rows and three columns, with . Take both rows and the last two columns. Their values are , giving . The sum reaches the upper bound, so no valid rectangle has a greater sum.

Input 2
1 3 3
2 2 -1
Output 2
3
Explanation 2
There is one row with values . Taking all three cells gives , equal to . This is the greatest valid sum.
Input 3
2 2 -12
-5 -6
-7 -8
Output 3
-12
Explanation 3
The single-cell rectangles have sums , all greater than . The two-cell rectangles have sums . The first column has sum , which reaches the bound. The entire grid sums to , below . Therefore the answer is .