Maximum Subarray 解答

时间:2021-10-05 12:22:57

Question

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.

Solution 1 -- DP

New array dp[i] has the following meaning:

dp[i] is the largest sum of subsequence (including nums[i]).

 public class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length < 1)
return 0;
int length = nums.length, result = nums[0];
int[] dp = new int[length];
dp[0] = nums[0];
for (int i = 1; i < length; i++) {
dp[i] = Math.max(nums[i], nums[i] + dp[i - 1]);
result = Math.max(result, dp[i]);
}
return result;
}
}

Solution 2

We can only use one variable instead of array.

 public class Solution {
public int maxSubArray(int[] nums) {
if (nums == null || nums.length < 1)
return 0;
int length = nums.length, result = nums[0], tmp = nums[0];
for (int i = 1; i < length; i++) {
tmp = Math.max(nums[i], nums[i] + tmp);
result = Math.max(result, tmp);
}
return result;
}
}