首页 > 其他 > 详细

[lintcode easy]Maximum Subarray

时间:2015-11-26 06:55:01      阅读:335      评论:0      收藏:0      [点我收藏+]

Maximum Subarray

Given an array of integers, find a contiguous subarray which has the largest sum.

 
Example

Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

Note

The subarray should contain at least one number.

Challenge

Can you do it in time complexity O(n)?

 

////similar as Minimum subarray

 

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        // write your code
        int sum=nums[0];
        int maxSum=nums[0];
        for(int i=1;i<nums.length;i++)
        {
            if(sum<0) sum=0;
            sum=sum+nums[i];
            maxSum=Math.max(maxSum,sum);
        }
        
        return maxSum;
    }
}

 

[lintcode easy]Maximum Subarray

原文:http://www.cnblogs.com/kittyamin/p/4996504.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!