Download Maximum subarray sum Example Solution 1: MaxsubSlow

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Maximum subarray sum
CSC 212: Data Structures and Abstractions
02: Maximum Subarray Problem
‣
Given an array of integers:
Marco Alvarez
A = [a1 , a2 , . . . , an ]
sj,k = aj + aj+1 + · · · + ak =
Department of Computer Science and Statistics
University of Rhode Island
Spring 2017
k
X
ai
i=j
Definition. The maximum subarray sum of array A is the sequence A[j : k], 0 
j  k  n that maximizes sj,k , the sum of its values.
Remark. By convention, the special array element A[0] = 0 is defined.
If all elements are negative, then the solution is an empty
subarray of zero sum.
2
Example
Solution 1: MaxsubSlow
‣
3
Apply Brute Force
✓
calculate the partial sums of every possible subarray
✓
for every sum, compare it to a running maximum and
update it if necessary
4
Example
A
0
Analysis
3
-4
1
-4
3
7
1
-2
O(n3 )
5
Solution 2: MaxsubFaster
‣
‣
Example
Wasting time calculating all partial sums
✓
consider using prefix sums
Prefix sums
✓
6
A
0
3
-4
1
-4
3
7
1
-2
S
0
3
-1
0
-4
-1
6
7
5
sum of the first t integers in A is denoted by:
t
X
St = a 1 + a 2 + · · · + a t =
ai
i=1
‣
Any subarray summation can be calculated by:
Sj,k = Sk
Sj
1
7
8
Analysis
Solution 3: MaxsubFastest
‣
Apply same idea …
✓
‣
consider using maximum suffix sums
Maximum suffix sums
✓
Mt is the summation value for a maximum subarray that
ends at t, denoted by:
Mt = max{0, max {sj,t }}
j=1,...,t
2
O(n )
‣
Any maximum suffix summation can be calculated
by:
Mt = max{0, Mt
1
+ A[t]}
9
Example
10
Analysis
A
0
3
-4
1
-4
3
7
1
-2
M
0
3
0
1
0
3
10
11
9
O(n)
11
12
Processing Power
Computational Cost
Size of
Input
MaxSubSlow
3
O(n )
MaxSubFaster
2
O(n )
MaxSubFastest
O(n)
n=1
1
1
1
n = 10
1,000
100
10
n = 100
1,000,000
10,000
100
n = 1000
1,000,000,000
1,000,000
1,000
n = 10000
1,000,000,000,000
100,000,000
10,000
n = 100000
1,000,000,000,000,000
10,000,000,000
100,000
n = 1000000
1,000,000,000,000,000,000
1,000,000,000,000
1,000,000
n = 10000000
1,000,000,000,000,000,000,000
100,000,000,000,000
10,000,000
http://pages.experts-exchange.com/processing-power-compared/
13
References
‣
Algorithm Design and Applications, Goodrich &
Tamassia
✓
Section 1.3
15
14
Related documents