File tree 1 file changed +67
-0
lines changed 1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n)
2
+ // Space: O(1)
3
+
4
+ // two pointers
5
+ class Solution {
6
+ public:
7
+ long long incremovableSubarrayCount (vector<int >& nums) {
8
+ int j = size (nums) - 1 ;
9
+ for (; j >= 1 ; --j) {
10
+ if (!(nums[j - 1 ] < nums[j])) {
11
+ break ;
12
+ }
13
+ }
14
+ if (j == 0 ) {
15
+ return (size (nums) + 1 ) * size (nums) / 2 ;
16
+ }
17
+ int64_t result = size (nums) - j + 1 ;
18
+ for (int i = 0 ; i + 1 < size (nums); ++i) {
19
+ while (j < size (nums) && !(nums[i] < nums[j])) {
20
+ ++j;
21
+ }
22
+ result += size (nums) - j + 1 ;
23
+ if (!(nums[i] < nums[i + 1 ])) {
24
+ break ;
25
+ }
26
+ }
27
+ return result;
28
+ }
29
+ };
30
+
31
+ // Time: O(n^3)
32
+ // Space: O(1)
33
+ // brute force
34
+ class Solution2 {
35
+ public:
36
+ long long incremovableSubarrayCount (vector<int >& nums) {
37
+ int64_t result = 0 ;
38
+ for (int left = 0 ; left < size (nums); ++left) {
39
+ for (int right = left; right < size (nums); ++right) {
40
+ bool check = left == 0 || right == size (nums) - 1 || nums[left - 1 ] < nums[right + 1 ];
41
+ if (!check) {
42
+ continue ;
43
+ }
44
+ for (int i = 0 ; i + 1 < left; ++i) {
45
+ if (!(nums[i] < nums[i + 1 ])) {
46
+ check = false ;
47
+ break ;
48
+ }
49
+ }
50
+ if (!check) {
51
+ continue ;
52
+ }
53
+ for (int i = right + 1 ; i + 1 < size (nums); ++i) {
54
+ if (!(nums[i] < nums[i + 1 ])) {
55
+ check = false ;
56
+ break ;
57
+ }
58
+ }
59
+ if (!check) {
60
+ continue ;
61
+ }
62
+ ++result;
63
+ }
64
+ }
65
+ return result;
66
+ }
67
+ };
You can’t perform that action at this time.
0 commit comments