zoukankan      html  css  js  c++  java
  • 53. Maximum Subarray

    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.

     

    看《剑指offer》看到这道题,过来刷一下···

    class Solution {
    public:
        int maxSubArray(vector<int>& nums) {
            int cursum=0;
            int greatestsum=0x80000000;     //可以表示的最大的负数
            for(int i=0;i<nums.size();i++){
                if(cursum<=0)              //如果cursum为负,如果算上cursum会小于不算cursum开始的子数组的和,因此不需要前面的子数组,cursum扔掉
                    cursum=nums[i];
                else cursum+=nums[i];
                if(cursum>greatestsum)
                    greatestsum=cursum;
            }
            return greatestsum;
        }
    };
  • 相关阅读:
    数据结构算法练习(一)
    crontab详解
    git遇到问题
    docker容器管理
    docker及服务器遇到的坑
    shell study
    低级终端IO
    高级IO
    信号处理
    UNIX日期与时间
  • 原文地址:https://www.cnblogs.com/LUO77/p/5328182.html
Copyright © 2011-2022 走看看