53-Maximum SubArray

难度:easy

1.题目描述

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

2.算法分析

注:参考《剑指offer》

举例:输入的数组是{1,-2,3,10,-4,7,2,-5},首先sum初始化为1, 1+(-2) =
-1,当子数组{1,-2}加上后面的数字时只会减小总和,所以舍弃,sum从3开,3+10=13,当加上-4时,变成了9,此时<13,所以需要将13存储起来,因为再加上7的时候16就超过了13,所以前面存储的最大和改为16,接下来是同样的思想,知道遍历完整个数组。

3.代码实现

#include <iostream>
#include <vector>
using namespace std; 

int maxSubArray(vector<int>& nums);
int main() {
    int n;
    int value;
    vector<int> data; 
    cout << "the length of the array: ";
    cin >> n;
    for (int i = 0; i < n; ++i) {
        cin >> value;
        data.push_back(value);
    }
    cout << maxSubArray(data) << endl;
    return 0;
}
//  -2,1,-3,4,-1,2,1,-5,4
// output: 6
int maxSubArray(vector<int>& nums) {
    int n = nums.size();
    if (n == 0) return 0;
    int sum = nums[0];
    int greatestSum = sum;
    for (int i = 1; i < n; ++i) {
        if (sum > 0) {
            sum += nums[i];
        } else {
            sum = nums[i];
        }
        // need to save the greatest sum because when sum > 0 you may add some negative number and make it smaller
        if (sum > greatestSum) {
            greatestSum = sum;
        } 
    }
    return greatestSum; 
}

4.小结

主要注意一下当加上一个负数的时候需要将前面的最大值存储起来即可,这道题目比较简单,算法的时间复杂度是O(n).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值