Max Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 121563 Accepted Submission(s): 28137
Problem Description Given a sequence a[1],a[2],a[3]……a[n], your job is to calculate the max sum of a sub-sequence. For example, given (6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14. Input The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line starts with a number N(1<=N<=100000), then N integers followed(all the integers are between -1000 and 1000). Output For each test case, you should output two lines. The first line is “Case #:”, # means the number of the test case. The second line contains three integers, the Max Sum in the sequence, the start position of the sub-sequence, the end position of the sub-sequence. If there are more than one result, output the first one. Output a blank line between two cases. Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5 Sample Output
Case 1: 14 1 4 Case 2: 7 1 6
1. 分析:
此題是一道非常基礎的動態規劃題目,求數組的最大子序列和,我們可以用dp[i]表示數組中以a[i]爲結尾的最大子序列和,則有如下遞推公式:
dp[i]=max(dp[i-1]+a[i], a[i])
根據上述的遞推公式即可求出所有的dp[i],而程序所求即max(dp[i]).
觀察上述遞推公式,可以發現,dp[i+1]只依賴dp[i],因而只需要用一個變量sum保存當前的值dp[i],並更新保存max_sum = max(dp[i])即可
對於最大子序列區間,有三種方法:
- 根據遞推公式,可以跟蹤i的變化。在求最大值過程中,保存最大值的索引(i值),若dp[i] = dp[i-1] + a[i],則序列中肯定包含a[i-1], 若dp[i] = a[i],則序列從i處開始,從而求出區間。此方法需要保存各個dp[i]的值。
- 根據其最大值的結束位置,依次向前加,當sum == max_sum時,即爲其一個起始位置。(此題要求求出第一y個子序列,因而需要一直試探至數組起始位置)。(此方法不需要保存dp數組)
- 根據遞推公式,可發現,每次當dp[i]=a[i]時,即爲當前區間的起始位置,因此可以記錄該起始位置(下邊代碼用的正是該方法)
2. AC代碼:
#include <stdio.h>
int a[100000];
int main() {
int t, case_num;
case_num = 1;
scanf("%d", &t);
while (t--) {
int n;
scanf("%d", &n);
for (int i=0; i<n; i++)
scanf("%d", &a[i]);
int sum, max_sum, begin, end, pos;
sum = max_sum = a[0];
begin = end = pos = 0;
for (int i=1; i<n; ++i) {
sum = sum + a[i];
if (sum < a[i]) {
sum = a[i];
pos = i;
}
if (sum > max_sum) {
max_sum = sum;
begin = pos;
end = i;
}
}
printf("Case %d:\n%d %d %d\n", case_num++, max_sum, begin+1, end+1);
if (t) /////////////////////////////
puts("");
}
return 0;
}