Maximum Difference | Practice | GeeksforGeeks

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

Example(To be used only for expected output) :
Input:
2
3
2 1 8
7
2 4 8 7 7 9 3
Output
1
4
+1
sauravmehta8185 days ago
O(n) Solution
 
class Solution
{
   int findMaxDiff(int arr[], int n)
   {
       int[] output1=leftsmall(arr);
       int[] output2=rightsmall(arr);
       int num=Integer.MIN_VALUE;
       for(int i=0;i<arr.length;i++)
       {
           if(Math.abs(output1[i]-output2[i])>num)
               num=Math.abs(output1[i]-output2[i]);
       }
        return num;
   }
   public int[] leftsmall(int[] arr)
   {
       Stack<Integer> stk=new Stack<>();
       int[] output=new int[arr.length];
       stk.push(arr[0]);
       output[0]=0;
       for(int i=1;i<arr.length;i++)
       {
           while(!stk.empty() && stk.peek()>=arr[i])
               stk.pop();
           output[i]=stk.empty()? 0:stk.peek();
           stk.push(arr[i]);
       }
       return output;
   }
   
   
 public int[] rightsmall(int[] arr)
   {
       Stack<Integer> stk=new Stack<>();
       int[] output=new int[arr.length];
       stk.push(arr[arr.length-1]);
       output[arr.length-1]=0;
       for(int i=arr.length-2;i>=0;i--)
       {
           while(!stk.empty() && stk.peek()>=arr[i])
               stk.pop();
           output[i]=stk.empty()? 0:stk.peek();
           stk.push(arr[i]);
       }
       return output;
   }
}
0
bhavinbansal78652 weeks ago
int findMaxDiff(int a[], int n)   {     //Your code here     int left[n];     left[0]=0;     int k;     bool flag;          for(int i=1;i<n;i++)     {         k=i-1;         flag=false;                  while(k>=0)         {             if(a[i]>a[k])             {                left[i]=a[k];                flag=true;                break;              }             k--;         }                  if(flag==false)         left[i]=0;     }     int right[n];     right[n-1]=0;          for(int i=n-2;i>=0;i--)     {       k=i+1;       flag=false;                  while(k<=(n-1))         {             if(a[i]>a[k])             {                right[i]=a[k];                flag=true;                break;              }             k++;         }         if(flag==false)         right[i]=0;     }      int res=0;     for(int i=0;i<n;i++)     {         res=max(res,abs(left[i]-right[i]));     }          return res;   }
0
rawn963 weeks ago
	int findMaxDiff(int a[], int n)
    {
        stack<int> s;
        int ls[n]={0},ans=0;
        for(int i=0;i<n;i++){
            while(!s.empty() && a[s.top()]>a[i]){
                ans=max(ans,abs(ls[s.top()]-a[i]));
                s.pop();
            }
            if(!s.empty())
                ls[i]=a[s.top()]==a[i] ? ls[s.top()] : a[s.top()];
            s.push(i);
        }
        while(!s.empty()){
            ans=max(ans,ls[s.top()]);
            s.pop();
        }
        return ans;
    }
+1
ankitmaurya31 month ago
def nearestleftsmaller(a,n):
    ans = []
    stack = []
    for i in range(n):
        while(len(stack)!=0 and a[i]<=stack[-1]):
            stack.pop()
        if len(stack)==0:
            ans.append(0)
        else:
            ans.append(stack[-1])
#         ans.append(0 if len(stack)==0 else stack[-1])
        stack.append(a[i])
    return ans
    
def nearestrightsmaller(a,n):
    ans = [0 for i in range(n)]
    stack = []
    for i in range(n-1,-1,-1):
        while(len(stack)!=0 and a[i]<=stack[-1]):
            stack.pop()
        if len(stack)==0:
            ans[i] = 0
        else:
            ans[i] = stack[-1]
#         ans.append(0 if len(stack)==0 else stack[-1])
        stack.append(a[i])
    return ans
    
    
class Solution:
    # Your task is to complete this function
    # Function should return an integer denoting the required answer
    def findMaxDiff(self, a, n):
        nrs =  nearestrightsmaller(a,n)
        nls = nearestleftsmaller(a,n)
        res = 0
        for i in range(n):
            res = max(res,abs(nls[i]-nrs[i]))
        return res
0
anupamojha31131 month ago
 //Your code here      // Time Taken 0.01/1.29     int ans=0; for(int i=0;i<n;i++){     int r=0;int l=0;     for(int j=i;j<n;j++){         if(arr[i]>arr[j]){             r=arr[j];             break;         }     }      for(int j=i;j>=0;j--){         if(arr[i]>arr[j]){             l=arr[j];             break;         }     }     ans=max(ans,abs(l-r)); }     return ans;
0
21mx1261 month ago
//c++ program
 
vector<int> ls(n,0);     vector<int> stk;          stk.push_back(0);          for(int i=0;i<n;i++){         if(A[i]>stk[stk.size()-1]){             ls[i]=stk[stk.size()-1];             stk.push_back(A[i]);         }else{             while(A[i]<=stk[stk.size()-1]){                 stk.erase(stk.begin()+stk.size()-1);             }             ls[i]=stk[stk.size()-1];             stk.push_back(A[i]);         }     }          stk.clear();          stk.push_back(0);          int res=INT_MIN;          for(int i=n-1;i>=0;i--){                  if(A[i]>stk[stk.size()-1]){             //cout << stk[stk.size()-1] << " ";             res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1]));             stk.push_back(A[i]);         }else{             while(A[i]<=stk[stk.size()-1]){                 stk.erase(stk.begin()+stk.size()-1);             }             //cout << stk[stk.size()-1] << " ";             res = (res > abs(ls[i]-stk[stk.size()-1]) ? res : abs(ls[i]-stk[stk.size()-1]));             stk.push_back(A[i]);         }              }                    return res;
0
21mx126
This comment was deleted.
0
onlybkm20021 month ago
int findMaxDiff(int A[], int n)
    {
      stack<int> st1;
      stack<int> st2;
      vector<int> ls(n,0);
      vector<int> rs(n,0);
      for(int i=n-1; i>=0; i--)
      {
          while(!st1.empty() && st1.top()>=A[i])
          {
              st1.pop();
          }
          if(i<n)
          {
              if(!st1.empty())
              {
                  rs[i] = st1.top();
              }
          }
          st1.push(A[i]);
      }
      for(int i=0; i<n; i++)
      {
          while(!st2.empty() && st2.top()>=A[i])
          {
              st2.pop();
          }
          if(i<n)
          {
              if(!st2.empty())
              {
                  ls[i] = st2.top();
              }
          }
          st2.push(A[i]);
      }
      vector<int> diff(n);
      for(int i=0; i<n; i++)
      {
          diff[i] = abs(ls[i]-rs[i]);
      }
      int maxDiff = INT_MIN;
      for(int i=0; i<n; i++)
      {
          maxDiff = max(maxDiff,diff[i]);
      }
      return maxDiff;
    }
0
tooweaktooslow2 months ago
EASY JAVA SOLUTION
 
class Solution{   int findMaxDiff(int arr[], int n)   {       if(n==1)return 0;     Integer[] ls=new Integer[n];//left smaller    Integer[] rs=new Integer[n];//right smaller        Stack<Integer>st=new Stack<>();    findls(ls,arr,st,n);    st=new Stack<>();    findrs(rs,arr,st,n);   // System.out.println(Arrays.toString(ls));   int max=Integer.MIN_VALUE;   for(int i=0;i<n;i++)   {       int t=Math.abs(ls[i]-rs[i]);       if(t>max)max=t;   }    return max;       }   public static void findls(Integer[]ans,int[]arr,Stack<Integer>st,int n)   {       ans[0]=0;       st.push(arr[0]);       for(int i=1;i<n;i++)       {           if(st.size()>0 && st.peek()<arr[i])           {               ans[i]=st.peek();               st.push(arr[i]);           }           else{               if(st.size()==0)               {                   ans[i]=0;                   st.push(arr[i]);               }               else{                   while(st.size()>0 && st.peek()>=arr[i])                   {                       st.pop();                   }                   if(st.size()==0)                   {                       ans[i]=0;                   st.push(arr[i]);                   }                   else{                     ans[i]=st.peek();               st.push(arr[i]);                     }               }           }       }   }   public static void findrs(Integer[]ans,int[]arr,Stack<Integer>st,int n){       ans[n-1]=0;       st.push(arr[n-1]);       for(int i=n-2;i>=0;i--)       {           if(st.peek()<arr[i])           {              ans[i]=st.peek();              st.push(arr[i]);           }           else{               while(st.size()>0 && st.peek()>=arr[i])               {                   st.pop();               }               if(st.size()==0)               {                   ans[i]=0;                   st.push(arr[i]);               }else{                   ans[i]=st.peek();                   st.push(arr[i]);               }           }       }   }}
0
shubhankardey29sep2 months ago
class Solution
{
    int findMaxDiff(int a[], int n)
    {
	// Your code here	
	int []r1 = nsl(a,n);
	int []r2 = nsr(a,n);
	int max = 0;
	
	for(int i=0;i<n;i++)
	{
	    int res = Math.abs(r1[i] - r2[i]);
	    max = Math.max(max,res);
	}
	return max;
    }
    int[] nsl(int []a,int n)
    {
        Stack<Integer> st = new Stack<>();
        int []res = new int[n];
        res[0] = 0;
        st.push(a[0]);
        int idx = 1;
        for(int i=1;i<n;i++)
        {
            while(!st.isEmpty() && st.peek()>=a[i])
            st.pop();
            
            if(st.size()==0)
            res[idx++] = 0;
            
            else
            res[idx++] = st.peek();
            
            st.push(a[i]);
        }
        return res;
    }
    int[] nsr(int []a,int n)
    {
        Stack<Integer> st = new Stack<>();
        int []res = new int[n];
        res[n-1] = 0;
        st.push(a[n-1]);
        int idx = n-2;
        for(int i=n-2;i>=0;i--)
        {
            while(!st.isEmpty() && st.peek()>=a[i])
            st.pop();
            
            if(st.size()==0)
            res[idx--] = 0;
            
            else
            res[idx--] = st.peek();
            
            st.push(a[i]);
        }
        return res;
    }
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.