LeetCode_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.

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

}







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值