|
| 1 | +/* Maximum difference in an array |
| 2 | +Problem Statement Given an array of integers, a, return the maximum difference of any |
| 3 | +pair of numbers such that the larger integer in the pair occurs at a higher index (in the |
| 4 | +array) than the smaller integer. Return -1 if you cannot find a pair that satisfies this |
| 5 | +condition. |
| 6 | +Constraints: 1 ≤ N ≤ 1,000,000 -1,000,000 ≤ a[i] ≤ 1,000,000 ∀ i ∈ [0, N-1] |
| 7 | +Input Format: |
| 8 | +The first line of the input is N (the number of elements in the array), and then followed |
| 9 | +by N elements each in a separate line. |
| 10 | +Sample Input 0: |
| 11 | +8 |
| 12 | +Explanation 0: |
| 13 | +For the array { 2,3,10,2,4,8,1} given above, 10 is the largest number in the array and 1 |
| 14 | +is the smallest number in the array. However, the index of 10 is lower than the lowest |
| 15 | +index that contains a 1 so the condition of the problem is not satisfied. Using zero-based |
| 16 | +index notation, the correct answer is a[2] - a[0] = 10 - 2 = 8. This satisfies the condition |
| 17 | +that the larger number in the pair should be positioned at a higher index in the array |
| 18 | +than the smaller number. |
| 19 | +Sample Input 1: |
| 20 | +6 |
| 21 | +7 |
| 22 | +9 |
| 23 | +5 |
| 24 | +6 |
| 25 | +3 |
| 26 | +2 |
| 27 | +Sample Output 1: |
| 28 | +2 |
| 29 | +Explanation 1: |
| 30 | +The value of maxDifference is 9 - 7 = 2. 9 occurs at a[1] and 7 occurs at a[0]. This |
| 31 | +satisfies the condition that the larger number must have a higher index than the smaller |
| 32 | +number.*/ |
| 33 | + |
| 34 | + |
| 35 | +#include<stdio.h> |
| 36 | +void max_diff(int a[], int n){ |
| 37 | + int i,j,max; |
| 38 | + max = a[0] - a[1]; |
| 39 | + for(i=0;i<n;i++){ |
| 40 | + for(j=i+1;j<n;j++){ |
| 41 | + if((a[j] -a[i])>max && a[j] > a[i] && j>i ){ |
| 42 | + max = a[j] - a[i]; |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + printf("max difference = %d",max); |
| 47 | +} |
| 48 | +int main(){ |
| 49 | + int n,i,a[50]; |
| 50 | + printf("enter number of elements in array: "); |
| 51 | + scanf("%d",&n); |
| 52 | + printf("enter the %d elements of array: \n",n); |
| 53 | + for(i=0;i<n;i++){ |
| 54 | + scanf("%d",&a[i]); |
| 55 | + } |
| 56 | + max_diff(a,n); |
| 57 | + return 0; |
| 58 | +} |
| 59 | + |
| 60 | + |
| 61 | +/* OUTPUT: |
| 62 | +enter number of elements in the array: 7 |
| 63 | +enter the 7 elements of the array: |
| 64 | +2 |
| 65 | +3 |
| 66 | +10 |
| 67 | +2 |
| 68 | +4 |
| 69 | +8 |
| 70 | +1 |
| 71 | +max difference = 8 |
| 72 | +*/ |
0 commit comments