Question -
Given an array, your task is to find the maximum difference of arr[j] - arr[i] such that j>i.
Example -
Input : arr[] = {2, 3, 10, 6, 4, 8, 1}
Output : maximum difference is : 8
hint - maximum difference is of 10-2 = 8
Approach -
with the help of nested loop we solve this question with time O(n*n)
Implementation -
#include<iostream>
using namespace std;
void findmaxdifference(int arr[],int n)
{
int max=arr[1]-arr[0];
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(arr[j]-arr[i]>max)
max=arr[j]-arr[i];
}
}
cout<<"Maximum difference is : "<<max<<endl;
}
int main()
{
int n;
cout<<"Enter value of n : ";cin>>n;
int arr[n];
cout<<"Enter elements : "<<endl;
for(int i=0;i<n;i++)
cin>>arr[i];
findmaxdifference(arr,n);
return 0;
}
Time complexity - O(n*n)
Extra space - O(1)
Comments
Post a Comment