cur =Math.min(prevMin +nums.get(i),nums.get(i));minSum =Math.min(minSum, cur);prevMin = cur;
Approach 2 - Prefix Sum
此外还有一种思路是利用prefix sum,前缀和:
对于每一个位置 i ,我们维护
当前 prefix sum;
subarray 最小 prefix sum
subarray 最大 prefix sum
Solution
Kadane's Algorithm - O(1) space, O(n) time
publicclassSolution { /** * @param nums: a list of integers * @return: A integer indicate the sum of minimum subarray */publicintminSubArray(ArrayList<Integer> nums) {if (nums ==null||nums.size() ==0) {return0; }int size =nums.size();int min =Integer.MAX_VALUE;int prevMin =nums.get(0), minSum =nums.get(0);int cur =0;for (int i =1; i < size; i++) { cur =Math.min(prevMin +nums.get(i),nums.get(i)); prevMin = cur; minSum =Math.min(minSum, cur); }return minSum; }}
// dp[i] means the maximum subarray ending with A[i];
publicclassSolution { /** * @param nums: a list of integers * @return: A integer indicate the sum of minimum subarray */publicintminSubArray(ArrayList<Integer> nums) {if (nums ==null||nums.size() ==0) {return0; }int size =nums.size();int[] dp =newint[size]; dp[0] =nums.get(0);int minSum = dp[0];for (int i =1; i < size; i++) { dp[i] =Math.min(dp[i -1] +nums.get(i),nums.get(i)); minSum =Math.min(dp[i], minSum); }return minSum; }}
Prefix Sum Approach
publicclassSolution { /** * @param nums: a list of integers * @return: A integer indicate the sum of minimum subarray */publicintminSubArray(ArrayList<Integer> nums) {// write your codeint max =0, min =Integer.MAX_VALUE;int prefixSum =0;for(int i =0; i <nums.size(); i++){ prefixSum +=nums.get(i); min =Math.min(min, prefixSum - max); max =Math.max(max, prefixSum); }return min; }}