最大子串值
来源:互联网 发布:java旅游项目 编辑:程序博客网 时间:2024/04/27 23:19
void MaxSubseq_DP(int nums[], int count, int &resStart, int &resEnd, int &resMax){ // 求数组nums[]中连续子序列的最大和,并标出该子序列 // 设 f[x] 为以 a[x] 终止且包含 a[x] 的最大序列的和,有: // f[1] = a[1]; // f[x+1] = f[x] > 0 ? f[x] + a[x+1] : a[x+1] // 那么最大子序列的和就是 f[1] .. f[n] 中最大的一个 int start, max; int i; start = resStart = resEnd = 0; //初始化当前子序列和最大子序列为nums[0] max = resMax = nums[0]; for (i = 1; i < count; ++i) { if (max > 0) { max += nums[i]; } else{ max = nums[i]; //抛弃当前子序列 start = i; //开始新的子序列搜索 } if (resMax < max) { //更新最大子序列 resMax = max; resStart = start; resEnd = i; } }//for}