从零开始的LC刷题(13)*: Maximum Subarray

原题:

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

题意是求最大连续子串和,我觉得这道题完全不easy,暴力求法固然好写但是太弱逼,要达到O(n)需要想一段时间,不过代码确实比较简洁。思路是先设置一个csum用来不断计算附近连续的最大字串和,一旦新的元素 num[i] 比csum+num[i](即csum<0) 大,则用其来替换csum开始计算下一个区间的正连续字串和,同时设置一个计算结果的result,当附近最大和csum大于result时用把csum值赋给result,这样计算可以保证以下几点:

(1)csum低于0时放弃遍历过的子串,重新开始计算新的区间的和,可以保证旧区间和为负(即在新区间加上旧区间只会减少和

的值)时重新开始计算。

(2)result为所求的最大值

结果如下:

Success

Runtime: 8 ms, faster than 99.28% of C++ online submissions for Maximum Subarray.

Memory Usage: 9.4 MB, less than 98.90% of C++ online submissions for Maximum Subarray.

代码:

class Solution {
public:
    int maxSubArray(vector& nums) {
        int csum=0,result=INT_MIN;
        for(int i=0;i

 

你可能感兴趣的:(LEETCODE,C++)