53. Maximum Subarray

Posted 烁宝宝

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

代码如下:

 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的主要内容,如果未能解决你的问题,请参考以下文章

53. Maximum Subarray

53. Maximum Subarray

#Leetcode# 53. Maximum Subarray

53. Maximum Subarray

LeetCode 53. Maximum Subarray

53. Maximum Subarray