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.

31 comments on “CoCubes Programming Question – 2”


  • piyali

    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))


  • ritwikbasak07

    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);

    }
    }