-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathHOTELS.cpp
58 lines (46 loc) · 1.61 KB
/
HOTELS.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
#include<bits/stdc++.h>
using namespace std;
int main() {
//Total House and money
int n,m;
cin>>n>>m;
//Take cost of houses
long long arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
//mx will store max sum
//j will be starting index of current consecutive houses
//sum will be current sum of consecutive houses
long long mx = 0,j=0;
long long sum = 0;
//Loop over all houses
//Question will be find clusters of consecutive houses
//Which can sum upto given money
//We add a value to sum and if it will increase sum than money
//Then we start decreasing form start
for(int i=0;i<n;i++) {
//Added price of current house to current sum
sum += arr[i];
//if sum is greater than the money available
if(sum > m) {
//check if adding current consecutive houses maximum we can
//Is it maximum than previous maximum sum
mx = max(mx,sum-arr[i]);
//Now we have added a new value which has increased the total sum
//We need to decrease it. So decrease value by leaving out houses
//from start until we hit sum less than money so it will be our
//next sum of consecutive houses
while(sum > m && j <= i) {
sum -= arr[j];
j++;
}
//If we have found next consecutive sum then check if it is max
if(j!=i)
mx = max(mx,sum);
}else
//Else check if adding it to sum increase max
mx = max(mx,sum);
}
//Print the max value
cout<<mx<<endl;
}