lintcode最大子数组

最大子数组 

给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

 注意事项

子数组最少包含一个数

样例

给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

挑战 

要求时间复杂度为O(n)

标签 

相关题目 

分析:这里采用贪心法,时间复杂度为O(n),将子串和为负数的子串丢掉,只留和为正的子串。当前和为负,则再加下去越来越小,所以可以舍弃之前相加的和

class Solution {
public:
    /*
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    int maxSubArray(vector &nums) {
        // write your code here
        int n=nums.size();
        int ans=-1000000;//防止第一个出现很小的数字
        int sums=0;
        for(int i=0;ians)
            {
                ans=sums;
            }
            if(sums<0)
            {
                sums=0;
            }
        }
        return ans;
    }
};
时间复杂度为O(n2)的方法为

class Solution {  
public:  
    /** 
     * @param nums: A list of integers 
     * @return: A integer indicate the sum of max subarray 
     */  
    int maxSubArray(vector nums) {  
        // write your code here  
        int n = nums.size();  
        int ans = -1000000;  
        for(int i=0; i ans)  
                {  
                    ans = sum;  
                }  
            }  
        }  
        return ans;  
    }  
};  



你可能感兴趣的:(C/C++算法,lintcode,算法,lintcode,贪心,最大数组)