-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit-array-into-consecutive-subsequences.go
More file actions
69 lines (54 loc) · 1.13 KB
/
Copy pathsplit-array-into-consecutive-subsequences.go
File metadata and controls
69 lines (54 loc) · 1.13 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
package main
import (
"fmt"
"math"
)
// source: https://leetcode.com/problems/split-array-into-consecutive-subsequences/
func isPossible(nums []int) bool {
prevNum := math.MinInt32
state := [3]int{}
for len(nums) > 0 {
num := nums[0]
if prevNum+1 != num {
if state[1] != 0 || state[2] != 0 {
return false
}
state[0] = 0
}
count := 0
for len(nums) > 0 && nums[0] == num {
count++
nums = nums[1:]
}
count -= state[1] + state[2]
if count < 0 {
return false
}
state[0], state[1], state[2] = state[1]+min(count, state[0]), state[2], max(0, count-state[0])
prevNum = num
}
return state[1] == 0 && state[2] == 0
}
func min(i, j int) int {
if i < j {
return i
}
return j
}
func max(i, j int) int {
if i > j {
return i
}
return j
}
func main() {
// Example 1
var nums1 = []int{1, 2, 3, 3, 4, 5}
fmt.Println("Expected: true Output: ", isPossible(nums1))
// Example 2
var nums2 = []int{1, 2, 3, 3, 4, 4, 5, 5}
fmt.Println("Expected: true Output: ", isPossible(nums2))
// Example 3
var nums3 = []int{1, 2, 3, 4, 4, 5}
fmt.Println("Expected: false Output: ", isPossible(nums3))
}