Maximum Subarray 解答

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]).

 1 public class Solution {
 2     public int maxSubArray(int[] nums) {
 3         if (nums == null || nums.length < 1)
 4             return 0;
 5         int length = nums.length, result = nums[0];
 6         int[] dp = new int[length];
 7         dp[0] = nums[0];
 8         for (int i = 1; i < length; i++) {
 9             dp[i] = Math.max(nums[i], nums[i] + dp[i - 1]);
10             result = Math.max(result, dp[i]);
11         }
12         return result;
13     }
14 }

Solution 2

We can only use one variable instead of array.

 1 public class Solution {
 2     public int maxSubArray(int[] nums) {
 3         if (nums == null || nums.length < 1)
 4             return 0;
 5         int length = nums.length, result = nums[0], tmp = nums[0];
 6         for (int i = 1; i < length; i++) {
 7             tmp = Math.max(nums[i], nums[i] + tmp);
 8             result = Math.max(result, tmp);
 9         }
10         return result;
11     }
12 }
原文地址:https://www.cnblogs.com/ireneyanglan/p/4822777.html