-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsumMaxMin.cpp
More file actions
66 lines (45 loc) · 1.4 KB
/
Copy pathsumMaxMin.cpp
File metadata and controls
66 lines (45 loc) · 1.4 KB
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
// sum of max min in cpp
#include<iostream>
#include<queue>
using namespace std;
int solve(int *arr, int n, int k) {
deque<int> maxi(k); // 2 dequeue bne hai maxi or mini nam ki
deque<int> mini(k);
// addition of first k size window
for(int i = 0; i < k; i++) {
while(!maxi.empty() && arr[maxi.back()] <= arr[i])
maxi.pop_back();
while(!mini.empty() && arr[mini.back()] >= arr[i])
mini.pop_back();
maxi.push_back(i);
mini.push_back(i);
}
int ans = 0;
ans += arr[max.front()] + arr[mini.front()];
// remaining windows ko process karlo
for(int i = k; i < n; i++) {
// next window
// removal
while(!maxi.empty() && i - maxi.front() >=k) {
maxi.pop_front();
}
while(!mini.empty() && i - mini.front() >=k) {
mini.pop_front();
}
//addition
while(!maxi.empty() && arr[maxi.back()] <= arr[i])
maxi.pop_back();
while(!mini.empty() && arr[mini.back()] >= arr[i])
mini.pop_back();
maxi.push_back(i);
mini.push_back(i);
ans += arr[maxi.front()] + arr[mini.front()];
}
return ans;
}
int main() {
int arr[7] = {2, 5, -1, 7, -3, -1, -2};
int k = 4;
cout << solve(arr, 7, k) << endl;
return 0;
}