53. Maximum Subarray
Posted Premiumlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了53. Maximum Subarray相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/maximum-subarray/description/
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.
Sol 1:
public class Solution { public int maxSubArray(int[] nums) { // DP // Time O(N) Space O(1) int maxLocal = nums[0]; int global = nums[0]; for (int i = 1; i < nums.length; ++i){ maxLocal = Math.max(nums[i], nums[i] + maxLocal); global = Math.max(global, maxLocal); } return global; } }
Sol 2:
(Unsolved -- don‘t know what cur_min is doing here...)
public class Solution { public int maxSubArray(int[] nums) { // Time O(n) Space O(n) return mcss(nums, 0, nums.length); } // find the max sum of the continuous array public static int mcss(int[] nums, int begin, int end){ final int n = end - begin; int[] sum = new int[n + 1]; // the sum of n elements in the front int result = Integer.MIN_VALUE; int cur_min = sum[0]; for (int i = 1; i <= n; i++){ sum[i] = sum[i - 1] + nums[begin + i - 1]; } for (int i = 1; i <= n; i++){ result = Math.max(result, sum[i] - cur_min); cur_min = Math.min(cur_min, sum[i]); } return result; } }
以上是关于53. Maximum Subarray的主要内容,如果未能解决你的问题,请参考以下文章