-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathmax_diff
More file actions
41 lines (33 loc) · 870 Bytes
/
max_diff
File metadata and controls
41 lines (33 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <limits.h>
// Utility function to find a maximum of two numbers
int max(int x, int y) {
return (x > y) ? x : y;
}
// Naive function to find the maximum difference between two elements in
// an array such that the smaller element appears before the larger element
int getMaxDiff(int arr[], int n)
{
int diff = INT_MIN;
if (n == 0) {
return diff;
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[j] > arr[i]) {
diff = max(diff, arr[j] - arr[i]);
}
}
}
return diff;
}
int main()
{
int arr[] = { 2, 7, 9, 5, 1, 3, 5 };
int n = sizeof(arr) / sizeof(arr[0]);
int result = getMaxDiff(arr, n);
if (result != INT_MIN) {
printf("The maximum difference is %d", result);
}
return 0;
}