Professional Documents
Culture Documents
Kadane
Kadane
Carlos Cotta
http://www.lcc.uma.es/∼ccottap
Index
Problem Context
We are given a photography and we wish to automatically identify
where the brightest spot is.
Problem Formulation
is maximal.
Exhaustive Search
We can naively explore all possible bounding boxes.
Naive approach
best ← −∞
for i1 ← 1 to m do
for j1 ← 1 to n do
for i2 ← i1 to m do
for j2 ← j1 to n do
sum ← BBox(i1 , j1 , i2 , j2 )
if sum > best then
best ← sum
it ← i1 ; jt ← j1 ; ib ← i2 ; jb ← j2
endif
endfor
endfor
endfor
endfor
i2
X
BBox(i1 , j1 , i2 , j2 ) = (Ck,j2 − Ck,j1 −1 )
k=i1
Hence,
(
0 i2 < i1
BBox(i1 , j1 , i2 , j2 ) =
BBox(i1 , j1 , i2 − 1, j2 ) + Ci2 ,j2 − Ci2 ,j1 −1 i2 ⩾ i1
1 2 3 4 5 6 7 8 9
-3 1 -8 12 0 -3 5 -9 4
1D-Kadane’s Algorithm
Subproblems considered
Si = maximum sum of any subarray finishing in position i (i.e.,
including position i).
Si = max(Si−1 + Ai , Ai )
1D-Kadane’s Algorithm
The final solution is S = max(Si | 1 ⩽ i ⩽ n).
1D-Kadane’s Algorithm
proc Kadane (↓A[1 . . . n]: R, ↑start, end: N, ↑S: R)
begin
S ← −∞
cur ← 0; j ← 1
for i ← 1 to n do
if cur < 0 then
cur ← Ai ; j ← i
else
cur ← cur + Ai
endif
if cur > S then
S ← cur ; start ← j; end ← i
endif
endfor
end
2D-Kadane’s Algorithm
In the 2D case, given j1 and j2 we use 1D-Kadane’s
Pj2 algorithm on
cumulative values from the matrix (Bi = j=j1 Aij ).
j1 j2
1 2 3 4 5 6 7 8 B
1 3 2 5 0 -4 5 1 1 3 1
2 -3 -2 -2 -4 4 0 4 -1 -4 2
3 -1 2 -4 7 3 4 -3 2 8 3
4 -4 -3 0 1 -4 -2 -3 4 -6 4
5 0 1 3 4 5 -1 -2 -3 13 5
6 1 -1 2 -3 -3 -4 -3 1 -5 6
2D-Kadane’s Algorithm
2D-Kadane’s Algorithm
best ← −∞
for j1 ← 1 to n do
for i ← 1 to m do Bi ← 0 endfor
for j2 ← j1 to n do
for i ← 1 to m do Bi ← Bi + Ai,j2 endfor
Kadane (B, start, end, S)
if S > best then
best ← S
it ← start; jt ← j1 ; ib ← end; jb ← j2
endif
endfor
endfor
The two outer nested loops (j1 and j2 ) perform Θ(n2 ) iterations.
In each of these, B is computed in Θ(m) and 1D-Kadane’s
algorithm is run in Θ(m) as well.
The overall time complexity is therefore Θ(mn2 ).
The space complexity is Θ(m).
Complementary Bibliography
J. Bentley,
“Programming Pearls: Algorithm Design Techniques”,
Communications of the ACM 27 (9): 865–873, 1984
doi: 10.1145/358234.381162
Image Credits