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
.
More practice:
Divide and Conquer Array Dynamic Programming
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Code:
/**
*
*/
package From41;
/**
* @author MohnSnow
* @time 2015年6月26日 上午8:57:53
*
*/
public class LeetCode53 {
/**
* @param argsmengdx
* -fnst
*/
//brute force---- Time Limit Exceeded
public static int maxSubArray(int[] nums) {
int maxSum = nums[0];
for (int i = 0; i < nums.length; i++) {
int sum = 0;
for (int j = i; j < nums.length; j++) {
sum += nums[j];
System.out.println("i: " + i + "j: " + j + "sum: " + sum);
maxSum = Math.max(sum, maxSum);
}
}
return maxSum;
}
//DP---http://wenchao.wang/?p=700----376msAC
//http://blog.csdn.net/joylnwang/article/details/6859677
//Kadane 算法的基本思想就是:如果当前和为负数,后面的数值加上当前和则必然小于原数值,则应将当前和丢弃。
public static int maxSubArray1(int[] nums) {
int tempSum = 0;
int maxSum = nums[0];
for (int i = 0; i < nums.length; i++) {
tempSum += nums[i];
maxSum = Math.max(maxSum, tempSum);
if (tempSum < 0)
tempSum = 0;
}
return maxSum;
}
public static void main(String[] args) {
int[] nums = { -2, -1, -3, 0 };
System.out.println("maxSubArray: " + maxSubArray(nums));
System.out.println("maxSubArray1: " + maxSubArray1(nums));
}
}