-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathWateringPlants.cpp
66 lines (46 loc) · 1.26 KB
/
WateringPlants.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
/*
Source: https://leetcode.com/problems/watering-plants/
Check at each steps if the water left in the water can is less than the capacity then,
count steps for going back to the river + coming back to water the plants, else just increment the steps as we proceed further
Time: O(n), where n is the size of the given vector(plants)
Space: O(1), constant space
*/
class Solution {
public:
int wateringPlants(vector<int>& plants, int capacity) {
int waterLeft = capacity;
int steps = 0;
int size = plants.size();
for(int i = 0; i < size; ++i) {
if(waterLeft < plants[i]) {
waterLeft = capacity;
steps += (i << 1) + 1;
} else {
steps += 1;
}
waterLeft -= plants[i];
}
return steps;
}
};
/*
Approach 2(Same as Approach 1, but more optimized)
Time: O(n), where n is the size of the given vector(plants)
Space: O(1), constant space
*/
class Solution {
public:
int wateringPlants(vector<int>& plants, int capacity) {
int waterLeft = capacity;
int steps = 0;
int size = plants.size();
for(int i = 0; i < size; ++i) {
if(waterLeft < plants[i]) {
waterLeft = capacity;
steps += (i << 1);
}
waterLeft -= plants[i];
}
return steps + size;
}
};