add: 220304-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-04 21:20:48 +08:00
parent 42bd393831
commit 1723ed7ada
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 38 additions and 1 deletions

37
cpp/2203/220304-CN.cpp Normal file
View File

@ -0,0 +1,37 @@
#include <vector>
#include <iostream>
/**
* 2104. Sum of Subarray Ranges
* You are given an integer array nums. The range of a subarray of nums is the difference between the largest and smallest element in the subarray.
* Return the sum of all subarray ranges of nums.
* A subarray is a contiguous non-empty sequence of elements within an array.
*/
class Solution {
private:
static inline constexpr int MAX(int x, int y) {
return x > y ? x : y;
}
static inline constexpr int MIN(int x, int y) {
return x < y ? x : y;
}
public:
static long long subArrayRanges(const std::vector<int>& nums) {
long long ret = 0;
int n = nums.size(), min, max;
for (int i = 1; i < n; ++i) {
ret += (max = MAX(nums[i - 1], nums[i])) - (min = MIN(nums[i - 1], nums[i]));
for (int j = i + 1; j < n; ++j)
ret += (max = MAX(nums[j], max)) - (min = MIN(nums[j], min));
}
return ret;
}
};
int main() {
std::cout << Solution::subArrayRanges({4,-2,-3,4,1});
return 0;
}

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220303.cpp) ADD_EXECUTABLE(2203 220304-CN.cpp)