Skip to content

Commit

Permalink
Create sum-of-beauty-in-the-array.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
kamyu104 authored Sep 20, 2021
1 parent 02a8298 commit bbeafa1
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions C++/sum-of-beauty-in-the-array.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// Time: O(n)
// Space: O(n)

class Solution {
public:
int sumOfBeauties(vector<int>& nums) {
vector<int> right(size(nums), nums.back());
for (int i = size(nums) - 2; i >= 2; --i) {
right[i] = min(right[i + 1], nums[i]);
}
int result = 0, left = nums.front();
for (int i = 1; i <= size(nums) - 2; ++i) {
if (left < nums[i] && nums[i] < right[i + 1]) {
result += 2;
} else if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) {
++result;
}
left = max(left, nums[i]);
}
return result;
}
};

0 comments on commit bbeafa1

Please sign in to comment.