 BiruLyu
6/15/2017 - 4:27 PM

## 53. Maximum Subarray(1st).java

``````class Solution {
public:
int maxSubArray(int A[], int n) {
int sum = 0, min = 0, res = A;
for(int i = 0; i < n; i++) {
sum += A[i];
if(sum - min > res) res = sum - min;
if(sum < min) min = sum;
}
return res;
}
};

/*
The idea is to find the largest difference between the sums when you summing up the array from left to right.
The largest difference corresponds to the sub-array with largest sum.
I worked it out independently although It is very close to lucastan's solution https://oj.leetcode.com/discuss/11288/simple-o-n-c-solution-no-dp-no-divide-and-conquer
*/``````
``````struct val {
int l, m, r, s;
val(int l, int m, int r, int s):l(l), m(m), r(r), s(s){}
};

class Solution {
public:
val dac(int A[], int n) {
if(n == 1) return val(A, A, A, A);
val v1 = dac(A, n / 2), v2 = dac(A + n / 2, n - n / 2);
int l, m, r, s;
l = max(v1.l, v1.s + v2.l);
m = max(v1.r + v2.l, max(v1.m, v2.m));
r = max(v2.r, v1.r + v2.s);
s = v1.s + v2.s;
return val(l, m, r, s);
}
int maxSubArray(int A[], int n) {
val v = dac(A, n);
return v.m;
}
};

/*
the idea is: for each sub array we calculate 4 values in O(1) time based on the return values of its two halves. The meaning of the values:

l: the sum of the sub array with largest sum starting from the first
element
m: the sum of the sub array with largest sum
r: the sum of the sub array with largest sum ending at the last
element
s: the sum of the whole array
the recursive relation is clear in the code.

*/``````
``````public class Solution {
public int maxSubArray(int[] nums) {
int res = Integer.MIN_VALUE;
if(nums == null || nums.length < 1) return res;
int len = nums.length;
int[] dp = new int[ len + 1];
for (int i = 1; i <= len; i++) {
dp[i] = nums[i - 1] + (dp[i - 1] < 0 ? 0 : dp[i - 1]);
res = Math.max(res, dp[i]);
}
return res;
}
}``````
``````public class Solution {
public int maxSubArray(int[] nums) {
int sum=0;
int max=Integer.MIN_VALUE;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
if(sum>max)
max=sum;
if(sum<0)
sum=0;
}
return max;
}
}``````