-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathform_num_divisible_by_3_sw.cpp
More file actions
53 lines (40 loc) · 978 Bytes
/
form_num_divisible_by_3_sw.cpp
File metadata and controls
53 lines (40 loc) · 978 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
42
43
44
45
46
47
48
49
50
51
52
53
// form a number that is divisible by 3 from a subarray using sliding window(sw)
#include<bits/stdc++.h>
using namespace std;
void formNumFromSubarr(vector<int> arr, int k) {
pair<int, int> ans;
int sum = 0;
for(int i=0; i<k; i++) {
sum += arr[i];
}
bool found = false;
if(sum % 3 == 0) {
ans = make_pair(0, k-1);
found = true;
}
for(int i=k; i<arr.size(); i++) {
if(found) {
break;
}
sum += (arr[i] - arr[i-k]);
if(sum % 3 == 0) {
ans = make_pair(i-k+1, i);
found = true;
}
}
if(found) {
for(int i=ans.first; i<=ans.second; i++) {
cout<<arr[i]<<" ";
}
cout<<endl;
} else
{
cout<<"No such subarray exists that is divisble by 3"<<endl;
}
}
int main() {
vector<int> arr = {84, 23, 45, 12, 56, 82};
int k = 3;
formNumFromSubarr(arr, k);
return 0;
}