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.

#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;
}

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

19 comments on “CoCubes Programming Question – 2”


  • surya

    l=[1,2,3,4,5]
    n=len(l)
    b=0
    for i in range(n):
    for j in range(i+1,n):
    if(l[j]>l[i]):
    a=l[j]-l[i]
    if(a>b):
    b=a
    print(b)


  • IPE2K17

    PYTHON 3.8

    n = list(map(int, input().split()))
    n.sort()
    diff= n[len(n)-1]-n[0]
    print(diff)


  • Sourabh

    #include”bits/stdc++.h”
    #define ll long long
    using namespace std;
    void cal()
    {
    int res[] = {2, 3, 10, 6, 4, 8, 1}; // 7, 9, 5, 6, 3, 2
    int len = sizeof(res) / sizeof(res[0]);

    ll max=0;
    for(int i=0;i<len;i++)
    {

    for(int j=i+1;jmax && res[j]>res[i])
    {
    max = ans;
    }
    }

    }
    cout<<max;
    }

    int main()
    {
    cin.tie(0);
    ios::sync_with_stdio(false);

    cal();

    return 0;

    }


  • Sakshi

    l=[int(x) for x in input().split()]
    m=0
    for i in range(0,len(l)):
    ele=l[i]
    for j in range(i+1, len(l)):
    diff=l[j]-l[i]
    if(diff>m):
    m=diff
    print(m)