Skip to content

Commit 1e0e4bb

Browse files
committed
2972. Count the Number of Incremovable Subarrays II
1 parent 8ec751a commit 1e0e4bb

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2972. Count the Number of Incremovable Subarrays II
5+
6+
// Two pointer
7+
// O(N)
8+
9+
func countSortedArrays(_ arr1: [Int], _ arr2: [Int]) -> Int {
10+
let n1 = arr1.count
11+
let n2 = arr2.count
12+
13+
var result = 0
14+
var i = 0
15+
var j = 0
16+
17+
while i < n1 && j < n2 {
18+
if arr1[i] < arr2[j] {
19+
result += (n2 - j)
20+
i += 1
21+
} else {
22+
j += 1
23+
}
24+
}
25+
26+
return result
27+
}
28+
29+
func incremovableSubarrayCount(_ nums: [Int]) -> Int {
30+
let n = nums.count
31+
32+
if n == 1 {
33+
return 1
34+
}
35+
36+
var i = 0
37+
var j = n - 1
38+
var arr1: [Int] = []
39+
var arr2: [Int] = []
40+
41+
while (i + 1) < n && nums[i] < nums[i + 1] {
42+
arr1.append(nums[i])
43+
i += 1
44+
}
45+
arr1.append(nums[i])
46+
47+
while (j - 1) >= 0 && nums[j] > nums[j - 1] {
48+
arr2.append(nums[j])
49+
j -= 1
50+
}
51+
arr2.append(nums[j])
52+
arr2.reverse()
53+
54+
if j < i {
55+
let ans = n * (n + 1) / 2
56+
return ans
57+
}
58+
59+
var ans = 0
60+
ans += arr1.count // 1
61+
ans += arr2.count // 2
62+
ans += countSortedArrays(arr1, arr2) // 3
63+
ans += 1 // 4
64+
65+
return ans
66+
}
67+
}

0 commit comments

Comments
 (0)