CoCubes Programming Question – 2
Maximum difference between two elements such that larger element appears after the smaller number
Given an array arr[] of integers, find out the difference between any two elements such that larger element appears after the smaller number in arr[].
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)
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Use two loops. In the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far.
- C
- Java
C
Java
C
#include<stdio.h> int maxDiff (int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } int main () { int len, i; printf( "Enter the length of the array\n"); scanf("%d",&len); int arr[len]; printf( "Enter the elements of the array\n"); for( i=0; i<len; i++) { scanf("%d",&arr[i]); } printf ("Maximum difference is %d" , maxDiff (arr, len)); getchar (); return 0; }
Java
import java.util.*; class MaximumDifference { int maxDiff(int arr[], int arr_size) { int max_diff = arr[1] - arr[0]; int i, j; for (i = 0; i < arr_size; i++) { for (j = i + 1; j < arr_size; j++) { if (arr[j] - arr[i] > max_diff) max_diff = arr[j] - arr[i]; } } return max_diff; } public static void main(String[] args) { MaximumDifference maxdif = new MaximumDifference(); int arr[] = { 1, 2, 90, 10, 110 }; System.out.println("Maximum differnce is " + maxdif.maxDiff(arr, 5)); } }
Python Solution:
def any(lis):
max_diff=float(‘-inf’)
min_ele=lis[0]
n=len(lis)
for i in range(1,n):
if lis[i]max_diff:
max_diff=diff
return max_diff
lists=list(map(int,input().split(‘,’)))
print(any(lists))
Hey there, Thanks for commenting, kindly join our Discord server, our mentors will guide you further precisely will all your queries.🙌
class GFG {
static void printDistinct(int arr[], int n)
{
int m=0;
int index = 0;
for (int i = 0 ; i m){
m=arr[i];
index=i;
}
}
int n1 = m;
for (int i = 0 ; i < index; i++){
if (arr[i]<n1){
n1 = arr[i];
}
}
System.out.println(m-n1);
}
// Driver program
public static void main (String[] args)
{
int arr[] = {2, 3, 10, 6, 4, 8, 1};
int n = arr.length;
printDistinct(arr, n);
}
}
python working code:
a=[]
n=int(input())
for i in range(n):
a.append(int(input()))
max1=0
max2=0
for i in range(0,n):
for j in range(i+1,n):
if a[i]max1 :
max1=diff
if max1>max2:
max2=max1
print(max2)