最大子序列和

问题

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.

问题传送门 密码:mesa

思路分析

用动态规划的思想:

  • dp[i]的意思是以数组中第i个数字为结尾的最大子序列和的值。
  • 然后我们得出公式: dp[i + 1] = max(dp[i] + a[i], a[i])
  • 这样我们得到序列和以及序列结尾元素,如果想要得到序列起始元素,倒着加和即可
  • 时间复杂度为O(n)

代码

#include 
#include 
#include 
using namespace std;

int main(int argc, const char * argv[]) {
    int T, N;
    cin >> T;
    for (int i = 1; i <= T; ++ i) {
        cin >> N;
        vector<int> vec(N);
        int local_sum = 0, max_sum = INT_MIN, left = 0, right = 0;
        for (int j = 0; j < N; ++ j) {
            cin >> vec[j];
            if (local_sum < 0)
                left = j;
            local_sum = max(local_sum + vec[j], vec[j]);
            cout << local_sum << endl;
            if (local_sum > max_sum) {
                max_sum = local_sum;
                right = j;
            }
        }
        cout << "Case " << i << ":" << endl;
        cout << max_sum << " " << left + 1 << " " << right + 1 << endl;
        if (i != T) cout << endl;
    }
    return 0;
}

你可能感兴趣的:(c/c++,算法,github)