-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathincreasing-triplet-subsequence.go
69 lines (57 loc) · 1.35 KB
/
increasing-triplet-subsequence.go
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/increasing-triplet-subsequence/
// straight-forward greedy solution, TLE
/*func increasingTriplet(nums []int) bool {
n := len(nums)
for i := 0; i < n-2; i++ {
for j := i + 1; j < n-1; j++ {
if nums[i] < nums[j] {
for k := j + 1; k < n; k++ {
if nums[j] < nums[k] {
return true
}
}
}
}
}
return false
}*/
func increasingTriplet(nums []int) bool {
n := len(nums)
if n < 3 {
return false
}
s, ss := nums[0], math.MaxInt32
for i := 1; i < n; i++ {
switch x := nums[i]; {
case x < s:
s = x
case x > s && x < ss:
ss = x
case x > ss:
return true
}
}
return false
}
func main() {
numsb := []int{1, 5, 0, 4, 1, 3}
fmt.Println("Expected: false\tOutput: ", increasingTriplet(numsb))
numsa := []int{1, 2, 2, 1}
fmt.Println("Expected: false\tOutput: ", increasingTriplet(numsa))
nums := []int{0, 4, 2, 1, 0, -1, -3}
fmt.Println("Expected: false\tOutput: ", increasingTriplet(nums))
// Example 1
var nums1 = []int{1, 2, 3, 4, 5}
fmt.Println("Expected: true Output: ", increasingTriplet(nums1))
// Example 2
var nums2 = []int{5, 4, 3, 2, 1}
fmt.Println("Expected: false Output: ", increasingTriplet(nums2))
// Example 3
var nums3 = []int{2, 1, 5, 0, 4, 6}
fmt.Println("Expected: true Output: ", increasingTriplet(nums3))
}