Professional Documents
Culture Documents
1
ACME CORP – PROFIT HISTORY
Year 1 2 3 4 5 6 7 8 9
Profit M$ -3 2 1 -4 5 2 -1 3 -1
Examples:
Between years 1 and 9 ACME earned
−3 + 2 + 1 − 4 + 5 + 2 − 1 + 3 − 1 = 4 M$
and between years 2 and 6
2 + 1 − 4 + 5 + 2 = 6 M$.
2
FORMAL DEFINITION
x=i
3
Θ(n3) Solution: Brute Force
VMAX = A[1];
For i = 1 to N
For j = i to N
{%calculate V (i, j)
V = 0;
For x = i to j
V = V + A[x];
If V > VMAX then
VMAX = V ;
}
Return(VMAX);
4
Θ(n2) solution: Reuse data
x=i
VMAX = A[1];
For i = 1 to N
{V = 0;
For j = i to N
{%calculate V (i, j)
V = V + A[j];
If V > VMAX then
VMAX = V ;
}
Return(VMAX);
5
Θ(n log n) solution: Divide-and-Conquer
S_1 S_2
M M+1
A_1 A_2
A_1 = MCS on left containing A[M] A_2 = MCS on right containing A[M+1]
A= A_1 U A_2
6
Example:
1 -5 4 2 -7 3 6 -1 2 -4 7 -10 2 6 1 -3
1 -5 4 2 -7 3 6 -1 2 -4 7 -10 2 6 1 -3
Since
Value(S1) = 9 Value(S2) = 9 Value(A) = 13
the solution to the problem is A.
7
Finding A : The conquer stage
A_1 A_2
i M M+1 j
8
The Full Divide-and-Conquer Algorithm
M CS(A, i, j)
1. If i == j return (i, j)
2. Else
3. Find M CS(A, i, b i+j
2 c);
4. Find M CS(A, b i+j2 c + 1, j);
5. Find MCS that contains
i+j i+j
both A b 2 c and A b 2 c + 1 ;
6. Return Maximum of the three sequences found
⇒ T (N ) = O(N log N ).
9
Analysis of a Simple D-and-C Algorithm
Note: For more details see CLRS, chapter 3.
T (n) ≤ 2 T + c n
2
n n
≤ 2 2 T 2 + c + c n
2 2
2
n
= 2 T 2 + 2c n
2
n n
≤ 22 2 T 3 + c 2 + 2c n
2 2
n
= 23 T 3 + 3c n
2
≤ ...
h
n
= 2 T h + hc n
2
Set h = log2 n, so that 2h = n.
With this substitution,
T (n) ≤ n T (1) + (log2 n)c n = O(n log2 n).
10
Simple Divide-and-Conquer Analysis: Takeaway
If an algorithm’s running time satisfies
n
T (n) ≤ 2 T + cn,
2
with initial condition T (1) = a, then
T (n) = O(n log n).
• Also,
n
if T (n) = 2 T 2 +cn ⇒ T (n) = Θ(n log n).
11
(Re)Visualizing the Problem
3
2 1
−2
T[i]
1 −3 4
2
0
i
−1 3 −1
−2
−2 −4 3
−3
i 0 1 2 3 4 5 6 7 8 9 10
A[i] -2 3 1 -3 2 -4 3 -1 4 -2
T (i) 0 -2 1 2 -1 1 -3 0 -1 3 1
12
(Re)Visualizing the Problem
3
2 1
−2
T[i]
1 −3 4
2
0
i
−1 3 −1
−2
−2 −4 3
−3
i 0 1 2 3 4 5 6 7 8 9 10
A[i] -2 3 1 -3 2 -4 3 -1 4 -2
T (i) 0 -2 1 2 -1 1 -3 0 -1 3 1
13
Idea behind an O(n) algorithm
3. Update Information:
14
The actual O(n) algorithm
T = A[1]; V = A[1]
Tmin = min(0, T );
For j = 2 to N
{ T = T + A[j]; % update T (j)
If T − Tmin > V % If Vpossible > V
then V = T − Tmin;
If T < Tmin
then Tmin = T ;
}
Return(V );
15
Review
16