Array ( [0] => [1] => questions [2] => Arrays [3] => Max-difference- ) Arrays | Max difference | THE INQUISITIVE





Max difference

LEVEL:Beginner

Description

Given an array of integers. Maximum difference between two elements such that larger element appears after the smaller element.

Input Format

First line contains the size of the array. Next line contains the n integers separated by the spaces.

Output Format

Maximum element


Example 1:

Input
5
1 2 3 4 5
Output
4
Example 2:

Input
3
4 8 7 
Output
4
Example 3:

Input
7
1 1 1 1 1 1 1
Output
0

oops

Login to see Discussion




Approach

Approach1:

Step-i) intialise max with difference of 1st element and 2nd element.
Step-ii) Then iterate loop i from index 1 to n
Step-iii) Use other for loop j from i+1 and find difference between i th and j th index elements.
Step-iv) if the difference is maximum replace the difference with max.
Step-v) Return the max variable.

Time Complexity: O(n^2)
Space Complexity: O(n^2)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution