-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution2079.go
More file actions
73 lines (60 loc) · 1.26 KB
/
solution2079.go
File metadata and controls
73 lines (60 loc) · 1.26 KB
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
67
68
69
70
71
72
73
package solution2079
// ============================================================================
// 2079. Watering Plants
// URL: https://leetcode.com/problems/watering-plants/
// ============================================================================
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/2079
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_wateringPlantsV1
Benchmark_wateringPlantsV1-24 281480796 4.154 ns/op 0 B/op 0 allocs/op
Benchmark_wateringPlantsV2
Benchmark_wateringPlantsV2-24 295546256 4.055 ns/op 0 B/op 0 allocs/op
PASS
*/
func wateringPlantsV2(plants []int, capacity int) int {
steps := 0
c := capacity
for i := 0; i < len(plants); i++ {
switch {
case c >= plants[i]:
c -= plants[i]
plants[i] = 0
steps++
default:
c = capacity
c -= plants[i]
plants[i] = 0
steps += 1 + (2 * i)
}
}
return steps
}
func wateringPlantsV1(plants []int, capacity int) int {
d := 1
x := -1
c := capacity
steps := 0
for {
x += d
steps++
if x+d < 0 {
c = capacity
d = -d
continue
}
if c >= plants[x] {
c -= plants[x]
plants[x] = 0
} else {
d = -d
continue
}
if x+d >= len(plants) {
break
}
}
return steps
}