Skip to content

Commit

Permalink
feat(C++): Add 2294
Browse files Browse the repository at this point in the history
  • Loading branch information
euchangxian committed Nov 5, 2024
1 parent 6e89584 commit e83e558
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
40 changes: 40 additions & 0 deletions C++/2294-PartitionArraySuchThatMaximumDifferenceIsK/Solution.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
#include <algorithm>
#include <cstddef>
#include <cstdlib>
#include <vector>

using namespace std;
class Solution {
public:
int partitionArray(std::vector<int>& nums, int k) {
// Reduce the problem, again! The question may seem like it wants to
// disallow sorting, by mentioning the definition of a subsequence.
// But notice that the order of elements within each subsequence do not
// matter. We only want the minimum and maximum of each subsequence such
// that max - min <= k.
// Therefore, sorting allows us to reduce this problem into a sliding window
// question (a little modified, since we do not want all subarrays, but the
// minimum number of subarrays), where the leftmost and rightmost of the
// window differ by at most k.
if (nums.empty()) {
return 0;
}

std::sort(nums.begin(), nums.end());

// start with a singular partition => the entire array.
int partitions = 1;
int l = 0;
for (int r = 1; r < nums.size(); ++r) {
// try to move r rightwards until the condition nums[r] - nums[l] <= k
// is violated. Then we know that the elements in [l..r-1] belong to its
// partition.
if (nums[r] - nums[l] > k) {
++partitions;
l = r;
}
}

return partitions;
}
};
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ Now solving in C++. Like it.
| 2275 | LargestCombinationWithBitwiseANDGreaterThanZero | [![C++](assets/c++.svg)](C++/2275-LargestCombinationWithBitwiseANDGreaterThanZero/Solution.cpp) |
| 2285 | MaximumTotalImportanceOfRoads | [![C++](assets/c++.svg)](C++/2285-MaximumTotalImportanceOfRoads/Solution.cpp) |
| 2290 | MinimumObstacleRemovalToReachCorner | [![C++](assets/c++.svg)](C++/2290-MinimumObstacleRemovalToReachCorner/Solution.cpp) |
| 2294 | PartitionArraySuchThatMaximumDifferenceIsK | [![C++](assets/c++.svg)](C++/2294-PartitionArraySuchThatMaximumDifferenceIsK/Solution.cpp) |
| 2307 | CheckForContradictionsInEquations | [![C++](assets/c++.svg)](C++/2307-CheckForContradictionsInEquations/Solution.cpp) |
| 2326 | SpiralMatrixFour | [![C++](assets/c++.svg)](C++/2326-SpiralMatrixFour/Solution.cpp) |
| 2331 | EvaluateBooleanBinaryTree | [![Rust](assets/rust.svg)](Rust/2331-EvaluateBooleanBinaryTree/Solution.rs) [![C++](assets/c++.svg)](C++/2331-EvaluateBooleanBinaryTree/Solution.cpp) |
Expand Down

0 comments on commit e83e558

Please sign in to comment.