Original title URL: https://www.lintcode.com/problem/maximum-subarray-difference/description
Describe
Given an array of integers, find two non-overlapping sub-arrays A and B, making the absolute value of the difference of two sub-arrays | SUM (A)-sum (B) | Biggest.
Returns the maximum value for this difference.
A sub-array contains at least one number
Have you ever encountered this problem in a real interview?is aSample Example
Given array [1, 2, -3, 1], return 6
Challenge
The time complexity is O (n) and the spatial complexity is O (n)
Idea: two sub-arrays and the absolute value of the difference | SUM (A)-sum (B) | Maximum, that is, one of the largest and the other smallest.
Along with the solution of maximal subarray Ⅱ, we define four array leftmax,leftmin,rightmax,rightmin, respectively, save the maximal subarray of 0~i and the most small array and the largest subarray of i+1~n-1 and the most small array.
Traverse, calculate the maximum value of leftmax-rightmin and Rightmax-leftmin, and return the larger of the two.
AC Code:
classSolution { Public: /** * @param nums:a List of integers * @return: An integer indicate the value of maximum difference between Substrings*/ intMaxdiffsubarrays (vector<int> &nums) { //Write your code here intn=nums.size (); if(n==0) { return 0; } Vector<int> Leftmax (N,0); Vector<int> Leftmin (N,0); Vector<int> Rightmax (N,0); Vector<int> Rightmin (N,0); intI=0, Tempsum1,tempsum2,maxsum,minsum; leftmax[0]=leftmin[0]=maxsum=minsum=nums[0]; Tempsum1=tempsum2=0; for(i=0; i<n;i++) {Tempsum1+=Nums[i]; Tempsum2+=Nums[i]; if(tempsum1>maxsum) {Maxsum=Tempsum1; } if(tempsum1<0) {Tempsum1=0; } if(tempsum2<minsum) {Minsum=tempsum2; } if(tempsum2>0) {tempsum2=0; } Leftmax[i]=maxsum; Leftmin[i]=minsum; } rightmax[n-1]=rightmin[n-1]=maxsum=minsum=nums[n-1]; Tempsum1=tempsum2=0; for(i=n-1;i>0; i--) {Tempsum1+=Nums[i]; Tempsum2+=Nums[i]; if(tempsum1>maxsum) {Maxsum=Tempsum1; } if(tempsum1<0) {Tempsum1=0; } if(tempsum2<minsum) {Minsum=tempsum2; } if(tempsum2>0) {tempsum2=0; } rightmax[i-1]=maxsum; Rightmin[i-1]=minsum; } intdiff1=leftmax[0]-rightmin[0]; intdiff2=rightmax[0]-leftmin[0]; for(i=1; i<n-1; i++) { if(leftmax[i]-rightmin[i]>diff1) {diff1=leftmax[i]-Rightmin[i]; } if(rightmax[i]-leftmin[i]>diff2) {diff2=rightmax[i]-Leftmin[i]; } } intdiff=Max (DIFF1,DIFF2); returndiff; }};
45 Maximum sub-array difference