Q-7 Maximum Difference
Given array A[] of integers, the task is to complete the function findMaxDiff which finds the maximum absolute difference between nearest left and right smaller element of every element in array.If the element is the leftmost element, nearest smaller element on left side is considered as 0. Similarly if the element is the rightmost elements, smaller element on right side is considered as 0.
Examples:
Input : arr[] = {2, 1, 8}
Output : 1
Left smaller LS[] {0, 0, 1}
Right smaller RS[] {1, 0, 0}
Maximum Diff of abs(LS[i] - RS[i]) = 1
Input : arr[] = {2, 4, 8, 7, 7, 9, 3}
Output : 4
Left smaller LS[] = {0, 2, 4, 4, 4, 7, 2}
Right smaller RS[] = {0, 3, 7, 3, 3, 3, 0}
Maximum Diff of abs(LS[i] - RS[i]) = 7 - 3 = 4
Input : arr[] = {5, 1, 9, 2, 5, 1, 7}
Output : 1
Input:
The first line of input contains an integer T denoting the no of test cases. Then T test cases follow .Each test case contains an integer N denoting the size of the array A. In the next line are N space separated values of the array A.
Output:
For each test case output will be in a new line denoting the the maximum absolute difference between nearest left and right smaller element of every element in array.
Constraints:
1<=T<=100
1<=N<=100
1<=A[ ]<=100
// { Driver Code Starts import java.util.*; class GFG { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t>0) { int n = sc.nextInt(); int a[] = new int[n]; for(int i=0; i<n; i++) a[i] = sc.nextInt(); Solution ob = new Solution(); System.out.println(ob.findMaxDiff(a,n)); t--; } } }// } Driver Code Ends
class Solution { int findMaxDiff(int a[], int n) { // Your code here Stack<Integer> stk= new Stack<>(); Stack<Integer> stk1= new Stack<>(); int[] ls = new int[n]; int[] rs = new int[n]; stk.push(0); stk1.push(0); for(int i=0; i<n;i++) { if(stk.peek()<a[i]) { ls[i]=stk.peek(); stk.push(a[i]); } else { while(stk.peek()>=a[i]) stk.pop(); ls[i]=stk.peek(); stk.push(a[i]); } } for(int i=n-1; i>=0;i--) { if(stk1.peek()<a[i]) { rs[i]=stk1.peek(); stk1.push(a[i]); } else { while(stk1.peek()>=a[i]) stk1.pop(); rs[i]=stk1.peek(); stk1.push(a[i]); } } int[] result= new int[n]; for(int i=0; i<n;i++) { result[i]= Math.abs(ls[i]-rs[i]); } Arrays.sort(result); return result[n-1]; } }
Post a Comment
0 Comments