-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmax_diff.cpp
74 lines (58 loc) · 1.41 KB
/
max_diff.cpp
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
using namespace std;
/*
Given an array of integers, find max(arr[j] - arr[i]) such that j>i
ip: arr[] = {2, 3, 10, 6, 4, 8, 1}
op: 8
ip: arr[] = {7, 9, 5, 6, 3, 2}
op: 2
ip: arr[] = {30, 10, 8, 2}
op: -2
ip: arr[] = {10, 20, 30}
op: 20
Naive Approach:
initialise res as diff b/w first pair i.e arr[1]-arr[0]
Now we consider every pair for each element
we find diff and
if diff > curr_res, we update res
Time: O(n^2)
Efficient solution:
Traverse array from left to right
Keep track of minimum element that we have seen so far
For every element, subtract minimum element from it
and we see if the res > curr_ res, we update the res
Time: Theta(n)
eg: arr = [2, 3, 10, 6, 4, 8, 1]
initially,
res = arr[1] - arr[0] = 1
minVal = arr[0] = 2
j=1:
res = max(1, arr[1]-minVal) = (1, 3-2) = 1
minVal = min(2, arr[1]) = min(2, 3) = 2
j=2:
res = max(1, arr[1]-minVal) = (1, 3-2) = 1
*/
int maxDiff_naive(int arr[], int n)
{
int res = arr[1] - arr[0];
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
res = max(res, arr[j] - arr[i]);
return res;
}
int maxDiff_eff(int arr[], int n)
{
int minVal = arr[0], res = arr[1]-arr[0];
for (int i = 1; i < n; i++)
{
res = max(res, arr[i] - res);
if(minVal > arr[i])
minVal = arr[i];
}
return res;
}
int main()
{
int arr[] = {2, 3, 10, 6, 4, 8, 1};
cout << maxDiff_eff(arr, 7);
}