Topic link: click here
Meaning: Given a KKFor a sequence of K integers, the largest subsequence refers to the largest sum of all elements in the continuous subsequence. For example, given the sequence{− 2, 11, − 4, 13, − 5, − 2} \left\{-2, 11, -4, 13, -5, -2\right\}{ −2,11,−4,13,−5,− 2 } , the largest subsequence is{11, − 4, 13} \left\{11, -4, 13\right\}{ 11,−4,1 3 } , the maximum sum is20 202 0 . Now you need to find the largest sum, and the first and last numbers of the largest subsequence.
Ideas:
A detailed explanation about the maximum subsequence sum: click here
On the basis of the above code, how to find the first and last numbers of the largest subsequence?
Since the subsequences we are looking for are all disjoint, so in the variable sss clear0 0When 0 , record the first number of the largest subsequencestart starts t a r t ; when updating the answer, record the last number of the largest subsequencerrr , updatellat the same timel。
AC code:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 10010;
int a[N];
int main()
{
int n, x;
scanf("%d", &n);
for(int i = 0; i < n; i++) scanf("%d", &a[i]);
int ans = -1e9, s = 0;
int start = 0, l, r;
for(int i = 0; i < n; i++)
{
if(s < 0)
{
s = 0;
start = i;
}
s += a[i];
if(s > ans)
{
ans = s;
l = start, r = i;
}
}
if(ans < 0) ans = 0, l = 0, r = n - 1;
printf("%d %d %d", ans, a[l], a[r]);
return 0;
}
The WeChat public account "Algorithm Competition Job Search" is dedicated to explaining in detail the algorithm principles and templates involved in the competition and job search. Welcome to pay attention and communicate and progress together!