PAT chicken dish notes 1007 Maximum Subsequence Sum
Ideas:
This question is to find the largest sub-elements and columns and the corresponding position, this seems to be a standard template, my code is based on the idea to write their own, may be rather strange.
First take the first sequence of sub-columns as a maximum and, traversal sequence. Set the current traverse to the j-th element, the following occurs:
- sum <= 0 and j-th element> = '0', before sub-columns, the left portion, sum was normalized to this location update max
- SUM> 0 and the j-th element> 0, the current element include put in, updated max
- Other cases, passing unified
finally, determine what the value of max, max <0 outputs 0, and the head and tail elements.
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
int test[10001];
int main() {
int K,left=0,right=0,Max=-1,sum=0;
int i =0, j = 0;
scanf("%d", &K);
for (int i = 0; i < K; i++)
{
scanf("%d", &test[i]);
}
Max = test[0];
while (j < K)
{
if (sum<=0&&test[j]>=0)
{
i = j;
sum = test[j];
if (Max < sum)
{
left = i;
right = j;
Max = sum;
}
}else
if (sum > 0 && test[j] > 0)
{
sum += test[j];
if (Max < sum)
{
left = i;
right = j;
Max = sum;
}
}else
sum += test[j];
j++;
}
if(Max<0)
{
Max=0;
left=0;
right=K-1;
}
printf("%d %d %d", Max, test[left], test[right]);
return 0;
}