Reputation: 2480
Given a rectangular grid with width width
and height height
, a rectangle is defined by four natural numbers, left
, right
, top
, and bottom
, satisfying:
left < right
and top < bottom
;left
and right
in range [1, width]
;top
and bottom
in range [1, height]
.The corners of a rectangle are the positions of the grid at coordinates (left, top)
, (right, top)
, (left, bottom)
, and (right, bottom)
.
Given a rectangular grid of integers, the value of a rectangle is the sum of the numbers in the grid at the corners of the rectangle. Is there an efficient algorithm that, given such a grid, finds a rectangle with the maximum value? If necessary, we may constrain the range of numbers in the grid.
A brute force algorithm is quadratic in the size of the grid, width * height
, because there are linearly many choices for each pair (left, top)
and (right, bottom)
. But I am wondering if this problem can be solved in linear, linearithmic, or similar time.
Upvotes: 1
Views: 411
Reputation: 65427
Suppose that the grid is m×n with m≤n. Here's a O(m2 n)-time algorithm. For each pair of rows (m choose 2), compute their element-wise sum and consider the sum of the two greatest entries of the resulting vector.
Upvotes: 2