Wednesday, May 15, 2013

Maximum subsequence sum C++

Find the maximum subsequence sum of an array of integers which contains both positive and negative numbers and return the starting and ending indices within the array.

For example:

int array[] = {1, -2, -3, 4, 5, 7, -6}

The max subsquence sum is 4+5+7= 16 and start index is at 3 and end index is at 5.


思路:DP,用一个int maxsofar记录当前最大和,对每个元素记录包含此元素的最大和cursum,同时更新maxsofar,这样做一遍就行了。




  1. //assume n>0  
  2.   
  3. int maxsubsum(int A[], int n){  
  4.   
  5.   int maxsofar = A[0], cursum = A[0];  
  6.   
  7.   for(int i = 1; i < n; i++){  
  8.   
  9.     cursum = A[i] + max(cursum, 0);  
  10.   
  11.     maxsofar = max(maxsofar, cursum);  
  12.   
  13.  }  
  14.   
  15.  return maxsofar;  
  16.   
  17. }  

No comments:

Post a Comment