首页 > 其他 > 详细

53. Maximum Subarray

时间:2017-02-12 12:07:24      阅读:176      评论:0      收藏:0      [点我收藏+]

题目:

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.

 
2/11/2017, Java
犯的错误:
1. 没有考虑到全是负数的情况,最简单的方法就是把每个值分为两个范围来考虑:负,非负。负值的话与当前sum比较,决定是否重置sum;非负值的话,如果当前sum为负,重置sum
2. max的初始化也可以是nums[0],min_value更直观,但是都必须保证是对的。
 
没有做divide and conquer approach
 1 public class Solution {
 2     public int maxSubArray(int[] nums) {
 3         if (nums == null) return 0;
 4         int max = Integer.MIN_VALUE;
 5         int sum = 0;
 6      
 7         for (int i = 0; i < nums.length; i++) {
 8             if (nums[i] >= 0) {
 9                 if (sum < 0) sum = nums[i];
10                 else sum += nums[i];
11                 if (max < sum) max = sum;
12             } else {
13                 if (sum < nums[i]) sum = nums[i];
14                 else sum += nums[i];
15                 if (max < sum) max = sum;
16             }
17         }
18         return max;
19     }
20 }

 

53. Maximum Subarray

原文:http://www.cnblogs.com/panini/p/6390539.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!