Timeline
Timeline
2025-10-18
init
Greedy
Problem:
O(nk)
First sort, then greedily choose the smallest one that can be taken each time. In the case of , use a loop to find the next one.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 | using std::vector;class Solution { public: int maxDistinctElements(vector<int> &nums, int k) { int i, j; int n = nums.size(); int res = 1; int last_val; int offset; std::sort(nums.begin(), nums.end()); last_val = nums[i] - k; for (i = 1; i < n; i++) { offset = nums[i] - nums[i - 1]; if (offset == 0 && last_val != nums[i - 1] + k) { last_val = last_val + 1; res++; } else if (offset > 2 * k) { last_val = nums[i] - k; res++; } else { // 0 < offset <= 2*k for (j = 0; j < 2 * k + 1; j++) { if (nums[i] - k + j > last_val) { res++; last_val = nums[i] - k + j; break; } } } } return res; }};int main(){ Solution s; vector<int> vec = { 1, 2, 2, 3, 3, 4 }; s.maxDistinctElements(vec, 2);} |
O(n)
Only need to iterate once. The main idea is to optimize the case of . Where the next value is taken depends on nums[i] - k and last_val, and we enumerate the cases to avoid a loop traversal.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 | using std::vector;class Solution { public: int maxDistinctElements(vector<int> &nums, int k) { int i, j; int n = nums.size(); int res = 1; int last_val; int offset; std::sort(nums.begin(), nums.end()); last_val = nums[i] - k; for (i = 1; i < n; i++) { offset = nums[i] - nums[i - 1]; if (offset == 0 && last_val != nums[i - 1] + k) { last_val = last_val + 1; res++; } else if (offset == 0 && last_val == nums[i - 1] + k) { continue; } else if (offset > 2 * k) { last_val = nums[i] - k; res++; } else { // 0 < offset <= 2*k if (nums[i] - k > last_val) { last_val = nums[i] - k; res++; } else { last_val = last_val + 1; res++; } } } return res; }};int main(){ Solution s; vector<int> vec = { 1, 2, 2, 3, 3, 4 }; s.maxDistinctElements(vec, 2);} |
