That's the interview question that I failed back in the days. Nobody of my friends knows where the mistake is and why I've been told that I failed. That's why I decided to ask you to correct my solution Given an array of N integers. An integer K divides array into two subarrays.
Left part: A[0], A[1]...A[K]; Right part: A[K+1], A[K+2]... A[N-1]; Need to find the max possible absolute difference of max values in every subarray.
MaxDiff = Math.Abs(Max(A[0], A[1]...A[K]) - Max(A[K+1], A[K+2]... A[N-1])) Example 1: [1, 3, -3]. If K=1, max difference is |3-(-3)| = 6. Example 2: [4, 3, 2, 5, 1, 1]. If K=3, max difference is |5 - 1| = 4. Time and space complexity should be O(n). As I see space complexity of my solution is not O(n) already..
int getMaxDifference(int[]A){ int [] leftMax = new int [A.length]; int [] rightMax = new int [A.length]; int max1 = Integer.MIN_VALUE; int max2 = Integer.MIN_VALUE; int dif = 0; int maxDif = 0; for (int i = 0; i< A.length; i++){ if (A[i]>max1) {max1 = A[i];} leftMax[i] = max1; } for (int j = A.length-1; j>0; j--){ if (A[j]>max2) {max2 = A[j];} rightMax[j] = max2; } for (int k = 0; k<A.length; k++){ dif = Math.abs(leftMax[k] - rightMax[k]); if (dif>maxDif) {maxDif = dif;}} return maxDif; }
Need to find the max possible absolute difference of max values in every subarrayis that how the question was phrased? Max difference of the max values doesn't really make sense as there's only one option, maybe the question was the max difference or smt similar.0?for (int j = A.length-1; j>=0; j--)