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

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

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

#include <algorithm>
#include <vector>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param array int整型vector
     * @return int整型vector
     */
    vector<int> FindGreatestSumOfSubArray(vector<int>& array) {
        // write code here
        int last_value = 0;
        int cur_value = 0;
        int max_value = INT_MIN;
        int best_start = 0;
        int best_end = 0;
        int last_start = 0;
        int last_end = 0;
        for (int i = 0; i < array.size(); i++) {
            if (i == 0) {
                last_value = array[i];
                max_value = last_value;
            } else {
                if (last_value < 0) {
                    cur_value = array[i];
                    last_start = i;
                    last_end = i;
                    max_value = max(cur_value, max_value);

                } else {
                    cur_value = last_value + array[i];
                    last_end = i;
                }
                last_value = cur_value;
                if (cur_value >= max_value) {
                    best_start = last_start;
                    best_end = i;
                    max_value = cur_value;
                }
            }
        }
        vector<int> res(best_end - best_start + 1);
        copy(array.begin() + best_start, array.begin() + best_end + 1, res.begin());
        return res;
    }
};

在动态规划的过程中,记录最大子数组的起始位置和终止位置。

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务