Skip to content

Commit c289dce

Browse files
authored
Create README.md
1 parent 37d1eb8 commit c289dce

File tree

1 file changed

+195
-0
lines changed
  • 16 - Queue Data Structure Problems/01 - Linear Queue Problems/12 - Sum of Minimum and Maximum Elements of All Subarrays of Size K

1 file changed

+195
-0
lines changed
Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
<h1 align='center'>Sum - of - Minimum & Maximum - Elements - of All - Subarrays of - Size K</h1>
2+
3+
## Problem Statement
4+
5+
**Problem URL :** [Sum of Minimum and Maximum Elements of All Subarrays of Size K](https://www.geeksforgeeks.org/sum-minimum-maximum-elements-subarrays-size-k/)
6+
7+
8+
**Problem:** Given an array of integers and a window size \( k \), calculate the sum of the maximum and minimum elements for each sliding window of size \( k \).
9+
10+
**Example:**
11+
- Input: `arr = [2, 5, -1, 7, -3, -1, -2]`, \( k = 4 \)
12+
- Output: The result should be the sum of maximum and minimum elements for each of the sliding windows of size \( k \).
13+
14+
**Windows:**
15+
1. `[2, 5, -1, 7]` => Max = 7, Min = -1 => Sum = 6
16+
2. `[5, -1, 7, -3]` => Max = 7, Min = -3 => Sum = 4
17+
3. `[-1, 7, -3, -1]` => Max = 7, Min = -3 => Sum = 4
18+
4. `[7, -3, -1, -2]` => Max = 7, Min = -3 => Sum = 4
19+
20+
**Final Output:** The sum of these results for all windows.
21+
22+
## Problem Solution
23+
```cpp
24+
#include <iostream>
25+
#include <deque>
26+
using namespace std;
27+
28+
int solve(int *arr, int n, int k){
29+
deque<int> maxi(k);
30+
deque<int> mini(k);
31+
32+
// Addition of first k size window
33+
for(int i = 0; i < k; i++){
34+
while(!maxi.empty() && arr[maxi.back()] <= arr[i]) maxi.pop_back();
35+
while(!mini.empty() && arr[mini.back()] >= arr[i]) mini.pop_back();
36+
37+
maxi.push_back(i);
38+
mini.push_back(i);
39+
}
40+
41+
int ans = 0;
42+
ans += arr[maxi.front()] + arr[mini.front()];
43+
44+
// Process remaining windows
45+
for(int i = k; i < n; i++){
46+
47+
// next window
48+
// removal
49+
while(!maxi.empty() && i - maxi.front() >= k) maxi.pop_front();
50+
while(!mini.empty() && i - mini.front() >= k) mini.pop_front();
51+
52+
// Addition
53+
while(!maxi.empty() && arr[maxi.back()] <= arr[i]) maxi.pop_back();
54+
while(!mini.empty() && arr[mini.back()] >= arr[i]) mini.pop_back();
55+
56+
maxi.push_back(i);
57+
mini.push_back(i);
58+
59+
ans += arr[maxi.front()] + arr[mini.front()];
60+
}
61+
62+
return ans;
63+
}
64+
65+
int main() {
66+
int arr[7] = {2, 5, -1, 7, -3, -1, -2};
67+
int k = 4;
68+
69+
cout << "Result : " << solve(arr, 7, k) << endl;
70+
return 0;
71+
}
72+
```
73+
74+
## Problem Solution Explanation
75+
76+
Let’s go through the code line by line with examples:
77+
78+
```cpp
79+
#include <iostream>
80+
#include <deque>
81+
using namespace std;
82+
83+
int solve(int *arr, int n, int k) {
84+
deque<int> maxi(k); // Deque to store indices of max elements
85+
deque<int> mini(k); // Deque to store indices of min elements
86+
```
87+
- **Includes and Namespace:** The code includes the necessary headers and uses the `std` namespace.
88+
- **Function Signature:** `solve` takes an array, its size `n`, and the window size `k`.
89+
- **Deques Initialization:** Two deques are initialized to store indices of the maximum and minimum elements within the current window.
90+
91+
```cpp
92+
// Addition of first k size window
93+
for (int i = 0; i < k; i++) {
94+
while (!maxi.empty() && arr[maxi.back()] <= arr[i]) maxi.pop_back();
95+
while (!mini.empty() && arr[mini.back()] >= arr[i]) mini.pop_back();
96+
97+
maxi.push_back(i);
98+
mini.push_back(i);
99+
}
100+
```
101+
- **First Window Processing:** The loop runs for the first \( k \) elements:
102+
- For each element, we remove indices from the back of `maxi` if the current element is greater or equal (to maintain max).
103+
- Similarly, we remove indices from `mini` if the current element is smaller or equal (to maintain min).
104+
- Finally, we add the current index to both `maxi` and `mini`.
105+
106+
**Example for `k=4`:**
107+
- For `i=0`: `maxi=[0]`, `mini=[0]` (Element 2)
108+
- For `i=1`: `maxi=[1]`, `mini=[0,1]` (Element 5)
109+
- For `i=2`: `maxi=[1]`, `mini=[2]` (Element -1)
110+
- For `i=3`: `maxi=[3]`, `mini=[2]` (Element 7)
111+
112+
After this loop, `maxi` contains the index of the maximum element (7 at index 3) and `mini` contains the index of the minimum element (-1 at index 2).
113+
114+
```cpp
115+
int ans = 0;
116+
ans += arr[maxi.front()] + arr[mini.front()];
117+
```
118+
- **Initial Answer Calculation:** The sum of the maximum and minimum for the first window is calculated and stored in `ans`.
119+
120+
```cpp
121+
// Process remaining windows
122+
for (int i = k; i < n; i++) {
123+
```
124+
- **Sliding Window:** The loop processes the remaining windows.
125+
126+
```cpp
127+
// next window
128+
// removal
129+
while (!maxi.empty() && i - maxi.front() >= k) maxi.pop_front();
130+
while (!mini.empty() && i - mini.front() >= k) mini.pop_front();
131+
```
132+
- **Removing Out-of-Bound Indices:** This ensures that the indices in the deques are within the current window size by popping indices that are no longer valid.
133+
134+
```cpp
135+
// Addition
136+
while (!maxi.empty() && arr[maxi.back()] <= arr[i]) maxi.pop_back();
137+
while (!mini.empty() && arr[mini.back()] >= arr[i]) mini.pop_back();
138+
139+
maxi.push_back(i);
140+
mini.push_back(i);
141+
```
142+
- **Adding Current Element:** Similar to the first window, we remove elements that are not needed and then add the current index.
143+
144+
```cpp
145+
ans += arr[maxi.front()] + arr[mini.front()];
146+
}
147+
```
148+
- **Update Answer:** We add the sum of the current window’s maximum and minimum to `ans`.
149+
150+
```cpp
151+
return ans;
152+
}
153+
```
154+
- **Return Final Result:** The final sum is returned.
155+
156+
```cpp
157+
int main() {
158+
int arr[7] = {2, 5, -1, 7, -3, -1, -2};
159+
int k = 4;
160+
161+
cout << "Result : " << solve(arr, 7, k) << endl;
162+
return 0;
163+
}
164+
```
165+
- **Main Function:** Initializes the array and calls the `solve` function, printing the result.
166+
167+
### Time and Space Complexities
168+
169+
#### 1. **Space Complexity:**
170+
171+
- The space complexity is determined by the deques, which store indices.
172+
- The maximum size of both `maxi` and `mini` is \( k \), and they only hold at most \( k \) indices at a time.
173+
174+
**Space Complexity:**
175+
\[
176+
O(k)
177+
\]
178+
179+
#### 2. **Time Complexity:**
180+
181+
- The outer loop runs \( n - k + 1 \) times (for each sliding window).
182+
- Each inner while loop for both `maxi` and `mini` can remove elements up to \( k \) in the worst case for each iteration of the outer loop.
183+
- Hence, each element is added and removed from the deques at most once.
184+
185+
**Time Complexity:**
186+
\[
187+
O(n)
188+
\]
189+
190+
### Summary of Complexities:
191+
192+
- **Time Complexity:** \( O(n) \) - Efficiently processes each element a constant number of times.
193+
- **Space Complexity:** \( O(k) \) - Requires space for two deques of size at most \( k \).
194+
195+
This implementation efficiently computes the desired sums for sliding windows using the properties of deques to maintain maximum and minimum values, making it well-suited for large datasets.

0 commit comments

Comments
 (0)