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.
Solution1:DP
思路:
dp[i] means the maximum subarray ending with A[i];
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0); 当前面以i-1结尾的最大和dp[i-1]为负时,也就是加了前面的 还没有自己大的情况下,dp[i] = 自己A[i],反之继续累加。
Time Complexity: O(N) Space Complexity: O(N)
实现1_b: P with Space Optimization,只依赖与dp[i - 1] 所以可以优化空间
Time Complexity: O(N) Space Complexity: O(1)
Solution2:在累积sum(离散积分) 上找 递增上"/"的最大差
思路: 累积sum 上的 递增的最大差 是就 原序列连续子序列的最大和。
Solution3:Divide & Conquer 分治
思路: (Not finished)
Solution1a Code:
class Solution1a {
public int maxSubArray(int[] nums) {
int n = nums.length;
int[] dp = new int[n]; //dp[i] means the maximum subarray ending with A[i];
dp[0] = nums[0];
int g_max = nums[0];
for(int i = 1; i < n; i++){
dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
if(dp[i] > g_max) {
g_max = dp[i];
}
}
return g_max;
}
}
Solution1b Code:
class Solution1b {
public int maxSubArray(int[] nums) {
int cur_max = nums[0];
int g_max = nums[0];
for(int i = 1; i < nums.length; i++) {
cur_max = (nums[i] > cur_max + nums[i]) ? nums[i] : cur_max + nums[i];
if(cur_max > g_max) {
g_max = cur_max;
}
}
return g_max;
}
}
Solution2 Code:
class Solution2 {
public int maxSubArray(int[] nums) {
int accusum = 0, prev_g_min = 0;
int g_max = nums[0];
for(int i = 0; i < nums.length; i++) {
accusum += nums[i];
if(accusum - prev_g_min > g_max) {
g_max = accusum - prev_g_min;
}
// update prev_g_min
if(accusum < prev_g_min) {
prev_g_min = accusum;
}
}
return g_max;
}
}