[LeetCode] Partition Array Such That Maximum Difference Is K

2294. Partition Array Such That Maximum Difference Is K

You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences.

Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int partitionArray(vector<int>& A, int k) {
sort(begin(A), end(A));
int n = A.size(), res = 0;

for(int i = 0, ma = INT_MIN; i < n; i++) {
if(ma >= A[i]) continue;
else {
res++;
ma = A[i] + k;
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/05/PS/LeetCode/partition-array-such-that-maximum-difference-is-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.