Maximum Contiguous subsequent sum

advertisement

Maximum Contiguous subsequent sum

(Taken by Manish Billa)

Given numbers 3,-2,6,8,-9,12,7

Given sequence a1,a2,a3,a4,a5,a6,a7…..a

J

1 ≤ I ≤ J ≤ N example {-2,6,8}

J

Sum = ∑ a k

k=I

Total sum of the above set is 25

--- Steps to be followed

Go through all possible subsequences

Find there sum if it is > previous maximum

Update Maximum

Algorithm: max = A[0] for(i = 0 ;i < Size; i++) for(j = 0 ; j < Size; j++) if(SUM(A,i,j) > max) max = SUM(A,i,j)

Running time of this algorithm is O(N 3 )

Function SUM:

S=0 for( k = i; i<=j; k++)

S += A[k];

Note that the way Sum function is called it is doing lot of rework.

Rewritten code to improve running time. max = A[0] for(i = 0 ;i < Size; i++){

SUM=0

for(j = 0 ; j < Size; j++){

SUM += A[j]

} if(SUM > max) max = SUM

}

The New algorithm is having running time O(N 2 )

Example no 2

6,-1,3,-5,2,-7 8,2,-9,1,7 running sum 0, 6,5,8, 3, 5,-2

Discard sum at this point and start new sequence

New Sequence (has to be better or equal)

Now using this logic we can reduce the above algorithm to one for loop max = A[0]

SUM = 0 for(i = 0 ;i < Size; i++){

SUM += A[i]

If(SUM < 0)

SUM = 0 else if(SUM > max) max = SUM

}

Depth First Search

Basic Idea: Search down one path as far as you can go ;

When you can’t go any further “Backtrack” and try new route

Note the algorithm given below is also given in textbook

dfsearch(G){

Mark each node in G as unvisited for each node V in G if V is unvisited do dfs( V )

}

Note that the underlined step above tells us how many number of components are presents in the graph (i.e. number of times it is run) dfs( V ){

Mark node V as visited for each node n that is adjacent to v that is unmarked dfs( n)

}

Trace of the above algorithm using the graph given below:

D A N

K

E B C L

O

F G H M

I J p

Q

Trace

Component1 dfs(B)[2] dfs(C)[3] dfs(D)[4] dfs(A)[1] dfs(E)[5] dfs(F)[6] dfs(G)[7] dfs(N)[8] dfs(O)[9]

Component 2 dfs(H)[10] dfs(I)[11] dfs(J)[12]

Component 3

Componenet 4 dfs(K)[13] dfs(L)[14]

Component 5 dfs(M)[15] dfs(P)[16] dfs(Q)[17]

Running time is O(number of nodes in graph)

Download