Maximum Difference

PROBLEM :
Given an array C[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number in C[].
Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2). If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9).

Input:
The first line of input contains an integer T denoting the number of test cases.
The first line of each test case is N,N is the size of array.
The second line of each test case contains N input C[i].

Output:
Print the maximum difference between two element. Otherwise print -1

Constraints:
1 = T = 80
2 = N = 100
1 = C[i] = 500

Example:
Input:
2
7
2 3 10 6 4 8 1
5
1 2 90 10 110

Output:
8
109

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

#include<iostream>
using namespace std;
int main()
{
int t ;
cin>>t ;
while(t--)
{
   int no ;
   cin>>no ;
   int arr[no] ;
   for(int i=0;i<no;i++)
       cin>>arr[i] ;
 
   int diff[no-1] ;
   for(int i=0;i<no-1;i++)
       diff[i]=arr[i+1]-arr[i] ;
     
   int maxdiff=diff[0] ;
   for(int i=1;i<no-1;i++)
   {
       if(diff[i]+diff[i-1]>diff[i])
           diff[i]=diff[i]+diff[i-1] ;
     
       if(diff[i]>maxdiff)
           maxdiff=diff[i] ;
   }
 
   cout<<maxdiff<<endl ;
}
return 0;
}

--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION : O(n)  time O(1) space
--------------------------------------------------------------------------------

#include<bits/stdc++.h>
using namespace std;
int main()
{
int t ;
cin>>t ;
while(t--)
{
   int no ;
   cin>>no ;
   int arr[no] ;
   for(int i=0;i<no;i++)
       cin>>arr[i] ;
 
   int minSoFar=arr[0] ;
   int maxDiff=INT_MIN ;
 
   for(int i=1;i<no;i++)
   {
       int curr=arr[i]-minSoFar ;
     
       if(curr>maxDiff)
           maxDiff=curr ;
       if(arr[i]<minSoFar)
           minSoFar=arr[i] ;
   }
 
   cout<<maxDiff<<endl ;
}
return 0;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )