Skip to content

Commit

Permalink
Minimize the Maximum Difference of Pairs
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Sep 5, 2023
1 parent ca7c8bb commit 608ce74
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ add_task(min-cost-climbing-stairs)
add_task(min-stack)
add_task(minimize-deviation-in-array)
add_task(minimize-maximum-of-array)
add_task(minimize-the-maximum-difference-of-pairs)
add_task(minimum-absolute-difference-in-bst)
add_task(minimum-absolute-sum-difference)
add_task(minimum-ascii-delete-sum-for-two-strings)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_minimize_the_maximum_difference_of_pairs test.cpp)
28 changes: 28 additions & 0 deletions solutions/minimize-the-maximum-difference-of-pairs/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#pragma once

#include <algorithm>
#include <vector>

class Solution {
public:
int minimizeMax(std::vector<int> nums, int p) {
std::sort(nums.begin(), nums.end());
int left = 0, right = nums.back() - nums.front();
while (left < right) {
const auto middle = left + (right - left) / 2;
countValidPairs(nums, middle) >= p ? right = middle : left = middle + 1;
}
return left;
}

private:
int countValidPairs(const std::vector<int> nums, int threshold) {
int cnt = 0;
for (size_t i = 0; i + 1 < nums.size(); ++i) {
if (nums[i + 1] - nums[i] <= threshold) {
++cnt, ++i;
}
}
return cnt;
}
};
21 changes: 21 additions & 0 deletions solutions/minimize-the-maximum-difference-of-pairs/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
{
std::vector<int> nums{10, 1, 2, 7, 1, 3};
int p = 2;
REQUIRE(1 == Solution().minimizeMax(nums, p));
}
{
std::vector<int> nums{4, 2, 1, 2};
int p = 1;
REQUIRE(0 == Solution().minimizeMax(nums, p));
}
{
std::vector<int> nums{50};
int p = 0;
REQUIRE(0 == Solution().minimizeMax(nums, p));
}
}

0 comments on commit 608ce74

Please sign in to comment.