题解 | #最大连续子序列#

最大连续子序列

https://www.nowcoder.com/practice/afe7c043f0644f60af98a0fba61af8e7

//https://www.nowcoder.com/practice/afe7c043f0644f60af98a0fba61af8e7?tab=answerKey

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    int n;
    while (cin >> n) {
        if(n==0)
            continue;

        vector<int> num(n); //? n为0时会怎么处理
        int dp[n];
        int flag = 0;
        int maxn = 0;
        int left = 0;
        int right = 0;
        int tem = 0;

        for(auto &c:num){
            cin >> c;
            if(c>=0)
                flag = 1;
        }

        if(!flag){
            cout << 0 << ' ' << num.front() << ' ' << num.back() << endl;
            continue;

        }



        for(int i = 0;i<n;i++){
            if(i==0){
                dp[i] = num[i];
                maxn = dp[i];
                left = i;
                right = i;
            }
            else{
                dp[i] = max(num[i], dp[i-1]+num[i]);
                if(dp[i]==num[i])
                    tem = i;
                if(maxn<dp[i]){
                    maxn = dp[i];
                    left = tem;
                    right = i;
                }


            }
        }

            cout << maxn << ' ' << num[left] << ' ' << num[right] << endl;

    }
}

全部评论

相关推荐

已老实求offer😫:有点像徐坤(没有冒犯的意思哈)
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务