Bloomberg 05102012 [1]

来源:互联网 发布:快穿之那串数据有毒 编辑:程序博客网 时间:2024/05/17 03:27
/*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.*/#include <iostream>int main(){int left = 0;int right = 0;int curLeft = 0;int curRight = 0;int maxSum = 0;int curSum = 0;int a[] = {1, -2, -3, 4, 5, 7, -6};for(int i = 0; i < 7; i++){curSum += a[i];if(curSum > maxSum){curRight = i;left = curLeft;right = curRight;maxSum = curSum;}if(curSum <= 0){curSum = 0;curLeft = i + 1;}}printf("From: %d    To: %d\n", left, right);printf("Max Sum: %d\n", maxSum);for(int i = left; i <= right; i++){printf("%d ", a[i]);}return 0;}


原创粉丝点击