Maximum Subarray Difference
Given an array with integers.
Find two non-overlapping subarrays A and B, which |SUM(A) - SUM(B)|
is the largest.
Return the largest difference.
Example
For [1, 2, -3, 1]
, return 6
.
Note
The subarray should contain at least one number
Challenge
O(n) time and O(n) space.
public class Solution { /** * @param nums: A list of integers * @return: An integer indicate the value of maximum difference between two * Subarrays */ public int maxDiffSubArrays(int[] nums) { // write your code here if(nums==null ||nums.length==0) return 0; int n=nums.length; int res=0; int[] leftMax=new int[n]; int[] leftMin=new int[n]; int sumMax=nums[0]; int sumMin=nums[0]; leftMax[0]=sumMax; leftMin[0]=sumMin; for(int i=1;i<n;i++) { sumMax=Math.max(sumMax+nums[i],nums[i]); leftMax[i]=Math.max(leftMax[i-1],sumMax); sumMin=Math.min(sumMin+nums[i],nums[i]); leftMin[i]=Math.min(leftMin[i-1],sumMin); } int[] rightMax=new int[n]; int[] rightMin=new int[n]; sumMax=nums[n-1]; sumMin=nums[n-1]; rightMax[n-1]=sumMax; rightMin[n-1]=sumMin; for(int i=n-2;i>=0;i--) { sumMax=Math.max(sumMax+nums[i],nums[i]); rightMax[i]=Math.max(rightMax[i+1],sumMax); sumMin=Math.min(sumMin+nums[i],nums[i]); rightMin[i]=Math.min(rightMin[i+1],sumMin); } for(int i=0;i<n-1;i++) { if(res<Math.abs(leftMax[i]-rightMin[i+1])) res=Math.abs(leftMax[i]-rightMin[i+1]); if(res<Math.abs(leftMin[i]-rightMax[i+1])) res=Math.abs(leftMin[i]-rightMax[i+1]); } return res; } }
时间: 2024-10-17 08:34:03