add: 220226-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-02-26 00:48:17 +08:00
parent bcf02d6f9f
commit f8be64124f
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 28 additions and 1 deletions

27
cpp/2202/220226-CN.cpp Normal file
View File

@ -0,0 +1,27 @@
#include <vector>
/**
* 2016. Maximum Difference Between Increasing Elements
* Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].
* Return the maximum difference. If no such i and j exists, return -1.
*/
class Solution {
public:
static int maximumDifference(const std::vector<int>& nums) {
int ret = -1;
int s[1005]{}, pos = 0;
for (int i : nums) {
for (; pos && s[pos - 1] > i; pos--)
ret = std::max(s[pos - 1] - s[0], ret);
s[pos++] = i;
}
ret = std::max(ret, pos ? s[pos - 1] - s[0] : -1);
return ret ? ret : -1;
}
};
int main() {
Solution::maximumDifference({9,4,3,2});
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2202)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2202 220225.cpp) ADD_EXECUTABLE(2202 220226-CN.cpp)