diff --git a/CMakeLists.txt b/CMakeLists.txt index 3afdabf3..7ca38038 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -356,6 +356,7 @@ add_task(minimum-number-of-arrows-to-burst-balloons) add_task(minimum-number-of-days-to-make-m-bouquets) 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-operations-to-make-array-continuous) add_task(minimum-number-of-taps-to-open-to-water-a-garden) add_task(minimum-number-of-vertices-to-reach-all-nodes) add_task(minimum-one-bit-operations-to-make-integers-zero) diff --git a/solutions/minimum-number-of-operations-to-make-array-continuous/CMakeLists.txt b/solutions/minimum-number-of-operations-to-make-array-continuous/CMakeLists.txt new file mode 100644 index 00000000..f4ce77a9 --- /dev/null +++ b/solutions/minimum-number-of-operations-to-make-array-continuous/CMakeLists.txt @@ -0,0 +1 @@ +add_catch(test_minimum_number_of_operations_to_make_array_continuous test.cpp) diff --git a/solutions/minimum-number-of-operations-to-make-array-continuous/solution.hpp b/solutions/minimum-number-of-operations-to-make-array-continuous/solution.hpp new file mode 100644 index 00000000..c632ce20 --- /dev/null +++ b/solutions/minimum-number-of-operations-to-make-array-continuous/solution.hpp @@ -0,0 +1,21 @@ +#pragma once + +#include +#include + +class Solution { +public: + static int minOperations(std::vector nums) { + const auto n = nums.size(); + + std::sort(nums.begin(), nums.end()); + nums.erase(std::unique(nums.begin(), nums.end()), nums.end()); + + auto ans = n - 1; + for (auto it = nums.begin(); it != nums.end(); ++it) { + auto ub = std::upper_bound(it, nums.end(), *it + n - 1); + ans = std::min(ans, n - std::distance(it, ub)); + } + return ans; + } +}; diff --git a/solutions/minimum-number-of-operations-to-make-array-continuous/test.cpp b/solutions/minimum-number-of-operations-to-make-array-continuous/test.cpp new file mode 100644 index 00000000..cf63da4b --- /dev/null +++ b/solutions/minimum-number-of-operations-to-make-array-continuous/test.cpp @@ -0,0 +1,18 @@ +#include + +#include + +TEST_CASE("Simple") { + { + std::vector nums{4, 2, 5, 3}; + REQUIRE(0 == Solution::minOperations(nums)); + } + { + std::vector nums{1, 2, 3, 5, 6}; + REQUIRE(1 == Solution::minOperations(nums)); + } + { + std::vector nums{1, 10, 100, 1000}; + REQUIRE(3 == Solution::minOperations(nums)); + } +}