题目:
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
.
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
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 }
原文:http://www.cnblogs.com/panini/p/6390539.html