# DS02_Ch02b - 3 Compare the Algorithms Example...

This preview shows pages 1–4. Sign up to view the full content.

§3 Compare the Algorithms 〖 Example 〖 Given (possibly negative) integers A 1 , A 2 , …, A N , find the maximum value of . = j i k k A Max sum is 0 if all the integers are negative. Algorithm 1 int MaxSubsequenceSum ( const int A[ ], int N ) { int ThisSum, MaxSum, i, j, k; /* 1*/ MaxSum = 0; /* initialize the maximum sum */ /* 2*/ for ( i = 0; i < N; i++ ) /* start from A[ i ] */ /* 3*/ for ( j = i; j < N; j++ ) { /* end at A[ j ] */ /* 4*/ ThisSum = 0; /* 5*/ for ( k = i; k <= j; k++ ) /* 6*/ ThisSum += A[ k ]; /* sum from A[ i ] to A[ j ] */ /* 7*/ if ( ThisSum > MaxSum ) /* 8*/ MaxSum = ThisSum; /* update max sum */ } /* end for-j and for-i */ /* 9*/ return MaxSum; } T ( N ) = O( N 3 ) Detailed analysis is given on p.18- 19. 1/9

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
Algorithm 2 §3 Compare the Algorithms int MaxSubsequenceSum ( const int A[ ], int N ) { int ThisSum, MaxSum, i, j; /* 1*/ MaxSum = 0; /* initialize the maximum sum */ /* 2*/ for ( i = 0; i < N; i++ ) { /* start from A[ i ] */ /* 3*/ ThisSum = 0; /* 4*/ for ( j = i; j < N; j++ ) { /* end at A[ j ] */ /* 5*/ ThisSum += A[ j ]; /* sum from A[ i ] to A[ j ] */ /* 6*/ if ( ThisSum > MaxSum ) /* 7*/ MaxSum = ThisSum; /* update max sum */ } /* end for-j */ } /* end for-i */ /* 8*/ return MaxSum; } T ( N ) = O( N 2 ) 2/9
§3 Compare the Algorithms Algorithm 3 Divide and Conquer 4 - 3 5 - 2 - 1 2 6 - 2 conquer divide 4 5 6 2 6 8 11

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern