From 79a980984afd2ed89b58a10ed33277fcda3eb7da Mon Sep 17 00:00:00 2001 From: Manuel Pineda Date: Thu, 14 Jan 2021 20:36:56 +0100 Subject: [PATCH] [LeetCode] Add January 14. --- solved/LeetCode/Challenges/2020/January/14.cc | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 solved/LeetCode/Challenges/2020/January/14.cc diff --git a/solved/LeetCode/Challenges/2020/January/14.cc b/solved/LeetCode/Challenges/2020/January/14.cc new file mode 100644 index 00000000..42ca8b8c --- /dev/null +++ b/solved/LeetCode/Challenges/2020/January/14.cc @@ -0,0 +1,54 @@ + +#include + +using namespace std; + +#include "../../../template.cc" + +using int64 = long long int; + + +class Solution { +public: + int minOperations(vector& nums, int x) { + int target = accumulate(nums.begin(), nums.end(), 0) - x; + int j = 0; + int best = -1; + int acc = 0; + for (int i = 0; i < nums.size() && j < nums.size(); i++) { + while (j < nums.size() && acc < target) { + acc += nums[j]; + j++; + } + if (acc == target) { + best = max(best, j - i); + } + acc -= nums[i]; + } + if (best == -1) { + return best; + } + return nums.size() - best; + } +}; + +struct Test { + vector nums; + int x; + int expected; +}; + +int main() { + vector test = { + { {1,1,4,2,3}, 5, 2}, + { {5,6,7,8,9}, 4, -1}, + { {3,2,20,1,1,3}, 10, 5}, + }; + for (auto t : test) { + Solution sol; + int actual = sol.minOperations(t.nums, t.x); + debug(t.nums, t.x, t.expected, actual); + assert(t.expected == actual); + } + return 0; +}