add: 221026-CN

This commit is contained in:
Eatswap 2022-10-26 14:32:55 +08:00
parent 375e18c9b8
commit f428f19329
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 43 additions and 1 deletions

42
cpp/2210/221026-CN.cpp Normal file
View File

@ -0,0 +1,42 @@
#include <vector>
#include <utility>
#include <algorithm>
#include <iostream>
/**
* 862. Shortest Subarray with Sum at Least K
*
* Given an integer array nums and an integer k, return the length of the shortest non-empty subarray of nums with a sum of at least k. If there is no such subarray, return -1.
* A subarray is a contiguous part of an array.
*/
class Solution {
public:
static int shortestSubarray(const std::vector<int>& nums, int k) {
const int n = nums.size();
auto ans = unsigned(-1);
long long s[100008]{0}, sum = 0;
int t[100008]{-1}, pos = 1;
for (int i = 0; i < n; ++i) {
// pos -> i, current -> sum + nums[i]
sum += nums[i];
// Check whether it has OK solution
if (nums[i] > 0) {
auto it = std::upper_bound(s, s + pos, sum - k);
if (it == s + pos || it != s && *it > sum - k)
--it;
if (*it <= sum - k && 1 == (ans = std::min(ans, unsigned(i - t[it - s]))))
return 1;
}
while (pos && s[pos - 1] >= sum)
--pos;
s[pos] = sum;
t[pos++] = i;
}
return int(ans);
}
};
int main() {
std::cout << Solution::shortestSubarray({2, -1, 2}, 3);
}

View File

@ -3,4 +3,4 @@ PROJECT(2210)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2210 221025.cpp)
ADD_EXECUTABLE(2210 221026-CN.cpp)