Skip to content

Commit

Permalink
Minimum Operations to Reduce X to Zero
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Sep 20, 2023
1 parent 5b1f21e commit b8078e9
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ add_task(minimum-number-of-flips-to-convert-binary-matrix-to-zero-matrix)
add_task(minimum-number-of-increments-on-subarrays-to-form-a-target-array)
add_task(minimum-number-of-vertices-to-reach-all-nodes)
add_task(minimum-one-bit-operations-to-make-integers-zero)
add_task(minimum-operations-to-reduce-x-to-zero)
add_task(minimum-path-sum)
add_task(minimum-penalty-for-a-shop)
add_task(minimum-remove-to-make-valid-parentheses)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_minimum_operations_to_reduce_x_to_zero test.cpp)
31 changes: 31 additions & 0 deletions solutions/minimum-operations-to-reduce-x-to-zero/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#pragma once

#include <algorithm>
#include <numeric>
#include <vector>

class Solution {
public:
static int minOperations(const std::vector<int> &nums, int x) {
const auto sum = std::accumulate(nums.begin(), nums.end(), 0);
const auto length = maxSubArrayLen(nums, sum - x);
return length == -1 ? -1 : nums.size() - length;
}

private:
static int maxSubArrayLen(const std::vector<int> &nums, int target_sum) {
const int n = nums.size();
int window_sum = 0;
int length = -1;
for (int l = 0, r = 0; r < n; ++r) {
window_sum += nums[r];
while (window_sum > target_sum && l <= r) {
window_sum -= nums[l++];
}
if (window_sum == target_sum) {
length = std::max(length, r - l + 1);
}
}
return length;
}
};
26 changes: 26 additions & 0 deletions solutions/minimum-operations-to-reduce-x-to-zero/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
{
std::vector<int> nums{1, 1, 4, 2, 3};
const int x = 5;
REQUIRE(2 == Solution::minOperations(nums, x));
}
{
std::vector<int> nums{5, 6, 7, 8, 9};
const int x = 4;
REQUIRE(-1 == Solution::minOperations(nums, x));
}
{
std::vector<int> nums{3, 2, 20, 1, 1, 3};
const int x = 10;
REQUIRE(5 == Solution::minOperations(nums, x));
}
{
std::vector<int> nums{1, 2, 3, 4};
const int x = 10;
REQUIRE(4 == Solution::minOperations(nums, x));
}
}

0 comments on commit b8078e9

Please sign in to comment.