Skip to content

Commit 8f3a4c3

Browse files
committed
feat: solution: easy: adjacent-increasing-subarrays-detection-i.go
1 parent ac1e3ed commit 8f3a4c3

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package easy
2+
3+
// https://leetcode.com/problems/adjacent-increasing-subarrays-detection-i
4+
func hasIncreasingSubarrays(nums []int, k int) bool {
5+
n := len(nums)
6+
if k <= 0 || 2*k > n {
7+
return false
8+
}
9+
10+
increment := make([]int, n)
11+
increment[n-1] = 1
12+
for i := n - 2; i >= 0; i-- {
13+
if nums[i] < nums[i+1] {
14+
increment[i] = increment[i+1] + 1
15+
} else {
16+
increment[i] = 1
17+
}
18+
}
19+
20+
for i := 0; i <= n-2*k; i++ {
21+
if increment[i] >= k && increment[i+k] >= k {
22+
return true
23+
}
24+
}
25+
26+
return false
27+
}
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package easy
2+
3+
import "testing"
4+
5+
func TestHasIncreasingSubarrays(t *testing.T) {
6+
cases := []struct {
7+
nums []int
8+
k int
9+
want bool
10+
}{
11+
{
12+
nums: []int{1, 2, 3, 4, 5, 6},
13+
k: 3,
14+
// [1,2,3] and [4,5,6] are both strictly increasing
15+
want: true,
16+
},
17+
{
18+
nums: []int{10, 0},
19+
k: 1,
20+
// two adjacent singletons -> trivially true
21+
want: true,
22+
},
23+
{
24+
nums: []int{1, 2, 3},
25+
k: 2,
26+
// need 4 elements for two adjacent length-2 windows
27+
want: false,
28+
},
29+
{
30+
nums: []int{1, 2, 3, 4},
31+
k: 0,
32+
want: false,
33+
},
34+
{
35+
nums: []int{1, 2, 2, 3, 4, 5},
36+
k: 2,
37+
// possible windows starting at 3: [3,4] and [4,5] => true
38+
want: true,
39+
},
40+
{
41+
nums: []int{1, 2, 3, 4},
42+
k: 2,
43+
// [1,2] and [3,4] -> both increasing
44+
want: true,
45+
},
46+
{
47+
nums: []int{2, 5, 7, 8, 9, 2, 3, 4, 3, 1},
48+
k: 3,
49+
want: true,
50+
},
51+
{
52+
nums: []int{1, 2, 3, 4, 4, 4, 4, 5, 6, 7},
53+
k: 5,
54+
want: false,
55+
},
56+
{
57+
nums: []int{-15, 19},
58+
k: 1,
59+
want: true,
60+
},
61+
{
62+
nums: []int{5, 8, -2, -1},
63+
k: 2,
64+
want: true,
65+
},
66+
}
67+
68+
for _, tc := range cases {
69+
got := hasIncreasingSubarrays(tc.nums, tc.k)
70+
if got != tc.want {
71+
t.Fatalf("hasIncreasingSubarrays(%v, %d) = %v, want %v", tc.nums, tc.k, got, tc.want)
72+
}
73+
}
74+
}

0 commit comments

Comments
 (0)