1
2
3
|
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class Solution {
public int maxSubArray( int [] nums) {
int len=nums.length;
if (nums== null || len== 0 ) return 0 ;
int MAX=nums[ 0 ];
int curSum=nums[ 0 ];
for ( int i= 1 ;i<len;i++){
if (curSum> 0 ){
curSum+=nums[i];
} else {
curSum=nums[i];
}
MAX=Math.max(curSum,MAX);
}
return MAX;
}
} |
PS:第一种思路,逐渐累加循环。
还有一种思路,可以用动态规划做。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public class Solution {
public int maxSubArray( int [] nums) {
int len=nums.length;
if (nums== null || len== 0 ) return 0 ;
//dp[i]代表以nums[i]为结尾的最大和。
int [] dp= new int [len];
dp[ 0 ]=nums[ 0 ];
int MAX=dp[ 0 ];
for ( int i= 1 ;i<len;i++){
if (dp[i- 1 ]< 0 ){
dp[i]=nums[i];
} else {
dp[i]=dp[i- 1 ]+nums[i];
}
MAX=Math.max(dp[i],MAX);
}
return MAX;
}
} |
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1905435