-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathWateringPlants.java
66 lines (47 loc) · 1.57 KB
/
WateringPlants.java
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 length of the given array(plants)
Space: O(1), constant space
*/
class Solution {
public int wateringPlants(int[] plants, int capacity) {
int waterLeft = capacity;
int steps = 0;
int len = plants.length;
for(int i = 0; i < len; ++i) {
if(waterLeft < plants[i]) {
waterLeft = capacity;
steps += (i << 1) + 1; // (i << 1) is equivalent to (i * 2);
} else {
++steps;
}
waterLeft -= plants[i];
}
return steps;
}
}
/*
Approach 2(Same as Approach 1, but more optimized)
Time: O(n), where n is the length of the given array(plants)
Space: O(1), constant space
*/
class Solution {
public int wateringPlants(int[] plants, int capacity) {
int waterLeft = capacity;
int steps = 0;
int len = plants.length;
for(int i = 0; i < len; ++i) {
if(waterLeft < plants[i]) {
waterLeft = capacity;
steps += (i << 1);
}
waterLeft -= plants[i];
}
// here steps is increasing everytime as we move forward, so no need to add steps for each element repeatidly
// eg: [1, 2, 3, 4], capacity = 10, here it's guaranteed that we will take 4 steps.
// eg: [1, 2, 3, 4], capacity = 5, here it's guaranteed that we will take atleast 4 steps for sure.
return steps + len;
}
}