题解 | #连续子数组的最大和(二)#

连续子数组的最大和(二)

https://www.nowcoder.com/practice/11662ff51a714bbd8de809a89c481e21

#include <cstring>
class Solution {
public:
    vector<int> FindGreatestSumOfSubArray(vector<int>& array) {
        vector<int> result;
        int size = array.size();
        vector<int> dp(size, 0);
        dp[0] = array[0];
        int maxn = array[0];
        int L = 0, R = 0;
        int result_L = 0, result_R = 0;
        for (int i = 1; i < size; ++i) {
            R++;
            dp[i] = max(dp[i-1] + array[i], array[i]);
            if (dp[i-1] + array[i] < array[i]) {
                L = R;
            }
            if (dp[i] > maxn || 
                (dp[i] == maxn && (R-L+1) > (result_L - result_R + 1))) {
                    maxn = dp[i];
                    result_L = L;
                    result_R = R;
            }
        }
        for (int i = result_L; i <= result_R; ++i) {
            result.push_back(array[i]);
        }        
        return result;    
    }
};

空间压缩

class Solution {
public:
    vector<int> FindGreatestSumOfSubArray(vector<int>& array) {
        vector<int> result;

        int last_cur = array[0];
        int cur = 0;
        int maxn = array[0];

        int left = 0, right = 0;
        int result_left = 0, result_right = 0;
        for (int i = 1; i < array.size(); ++i) {
            right++;
            cur = max(last_cur + array[i], array[i]);
            if (last_cur + array[i] < array[i]) {
                left = right;
            }
            if (cur > maxn || (cur == maxn && right - left + 1 > result_right - result_left + 1)) {
                maxn = cur;
                result_left = left;
                result_right = right;
            }
            last_cur = cur;
        }
        for (int i = result_left; i <= result_right; ++i) {
            result.push_back(array[i]);
        }
        return result;
    }
};

2023-剑指-DP 文章被收录于专栏

2023-剑指-DP

全部评论

相关推荐

10-18 13:01
已编辑
西安理工大学 C++
小米内推大使:建议技能还是放上面吧,hr和技术面试官第一眼想看的应该是技能点和他们岗位是否匹配
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务