Maximum Subarray 最大子数组
Maximum Subarray 最大子数组
Maximum Subarray 最大子数组
• 发表于 5个月前
• 阅读 9
• 收藏 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.

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.

public class Solution {

public int maxSubArray(int[] nums) {

int res = Integer.MIN_VALUE, curSum = 0;

for (int num : nums) {

curSum = Math.max(curSum + num, num);

res = Math.max(res, curSum);

}

return res;

}

}

public class Solution {

public int maxSubArray(int[] nums) {

if (nums.length == 0) return 0;

return helper(nums, 0, nums.length - 1);

}

public int helper(int[] nums, int left, int right) {

if (left >= right) return nums[left];

int mid = left + (right - left) / 2;

int lmax = helper(nums, left, mid - 1);

int rmax = helper(nums, mid + 1, right);

int mmax = nums[mid], t = mmax;

for (int i = mid - 1; i >= left; --i) {

t += nums[i];

mmax = Math.max(mmax, t);

}

t = mmax;

for (int i = mid + 1; i <= right; ++i) {

t += nums[i];

mmax = Math.max(mmax, t);

}

return Math.max(mmax, Math.max(lmax, rmax));

}

}

×