-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMonotonicArray.cpp
108 lines (89 loc) · 2.11 KB
/
MonotonicArray.cpp
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// https://leetcode.com/problems/monotonic-array/submissions/
// Analysis : First Tried To implement it in 2 loop approach Then change it to single loop
// Approach : First Run a loop and check for every next element greater than prev one if not flag = false break the loop
// Then we will only process for decresing array if condition is false if true we simply return it in decreasing loop we do the same check for every next element less than previous one
// My Solution
bool isMontonic(Ints &nums) {
bool flag = false;
if (nums.size() == 1)
return true;
for (int i = 0; i < nums.size() - 1; i++) {
if (nums[i] <= nums[i + 1]) {
flag = true;
} else {
flag = false;
break;
}
}
if (!flag) {
for (int i = 0; i < nums.size() - 1; i++) {
if (nums[i] >= nums[i + 1]) {
flag = true;
} else {
flag = false;
break;
}
}
}
return flag;
}
// TC -> O(n)
// Approach name: Two Pass
class Solution {
public:
bool increasing(Ints &nums) {
for (int i = 0; i < nums.size() - 1; i++)
if (nums[i] >= nums[i + 1]) return false;
return true;
}
bool decreasing(Ints &nums) {
for (int i = 0; i < nums.size() - 1; i++)
if (nums[i] <= nums[i + 1]) return false;
return true;
}
bool isMontonic(Ints &nums) {
return increasing(nums) || decreasing(nums);
}
}
// Same as My Aproach but checking opposite
// Approach 3 : One Pass
class Soltion {
public:
int compare(int a, int b) {
if (a == b) return 0;
if (a < b) return -1;
if (a > b) return 1;
return 0;
}
bool onePass(Ints &A) {
int store = 0;
for (int i = 0; i < A.size() - 1; ++i) {
int c = compare(A[i], A[i + 1]);
if (c != 0) {
if (c != store && store != 0)
return false;
store = c;
}
}
return true;
}
};
// TC - O(n) A.S -O(1)
// Approach 4: Simple Variant of One Pass
class MonotonicArray
{
public:
MonotonicArray();
~MonotonicArray();
bool isMontonic(Ints &A) {
bool increasing = true;
bool decreasing = true;
for (int i = 0; i < A.size() - 1; ++i) {
if (A[i] > A[i + 1])
increasing = false;
if (A[i] < A[i + 1])
decreasing = false;
}
return increasing || decreasing;
}
};