TADM2E 8.25

From Algorithm Wiki
Jump to: navigation, search

This is just a special case of the maximum contiguous sum problem. Instead of computing the result for 0,n instead we compute for i,j. We use the same logic, but as per the question we return 3 values indicating the index positions i', j', and max for the maximum sum of the i'th through j'th numbers. Note that this solution has a worst case running time of O(n), and requires constant additional space. Also note that this solution does not appear, to me, to really be a 'dynamic programming' algorithm.

public static int[] maxsum(int i, int j, int[] a) {
	int max = Integer.MIN_VALUE;
	int cur_max = Integer.MIN_VALUE;
 
	int cm_i = i;
	int cm_j = i;
 
        int m_i = i;
	int m_j = i;
 
	for (; i <= j; i++) {
		int x = a[i];
 
		if(cur_max + x > x){
			cur_max += x;
			cm_j++;
		}else{
			cur_max = x;
			cm_i = cm_j = i;
		}
 
		if(cur_max > max){
			m_i = cm_i;
			m_j = cm_j;
 
			max = cur_max;
		}
 
	}
 
	return new int[] {m_i, m_j, max};
}