Skip to content

Commit f6b465f

Browse files
authored
Create count-hills-and-valleys-in-an-array.cpp
1 parent 7d76953 commit f6b465f

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Time: O(n)
2+
// Space: O(1)
3+
4+
// simulation, array
5+
class Solution {
6+
public:
7+
int countHillValley(vector<int>& nums) {
8+
int result = 0, inc = -1;
9+
for (int i = 0; i + 1 < size(nums); ++i) {
10+
if (nums[i] < nums[i + 1]) {
11+
result += (inc == 0) ? 1 : 0;
12+
inc = 1;
13+
} else if (nums[i] > nums[i + 1]) {
14+
result += (inc == 1) ? 1 : 0;
15+
inc = 0;
16+
}
17+
}
18+
return result;
19+
}
20+
};

0 commit comments

Comments
 (0)