码迷,mamicode.com
首页 > 其他好文 > 详细

53. Maximum Subarray

时间:2016-05-17 19:12:32      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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.

代码如下:

 1 public class Solution {
 2     public int maxSubArray(int[] nums) {
 3         int max=nums[nums.length-1];
 4         int sum=0;
 5         int re=nums[0];
 6         for(int i=0;i<nums.length-1;i++)
 7         {
 8             if(nums[i]>=0)
 9             sum=nums[i];
10             else {
11                 if(re<nums[i])
12                 re=nums[i];
13                 continue;
14             }
15             if(max<sum)
16             max=sum;
17             for(int j=i+1;j<nums.length;j++)
18             {
19                 sum=sum+nums[j];
20                 if(sum>max)
21                 max=sum;
22             }
23         }
24 
25         if(re>max)
26         max=re;
27         return max;
28     }
29 }

 

53. Maximum Subarray

标签:

原文地址:http://www.cnblogs.com/ghuosaao/p/5502555.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!