您的位置:首页 > 编程语言 > Java开发

LeetCode_53---Maximum Subarray

2015-06-26 09:11 483 查看
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
.
click to show more practice.
More practice:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Hide Tags
 Divide and Conquer Array Dynamic
Programming

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));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 算法 java