LeetCode 2779. Maximum Beauty of an Array After Applying Operation

25 阅读1分钟

🔗 leetcode.com/problems/ma…

题目

  • 给定一个由数字组成的数组,和一个数字 k
  • 可以对其中任一 index 进行数字替换,替换为 [nums[i] - k, nums[i] + k] 中的任一数字
  • 每一个元素最多能被替换一次
  • 返回经过替换,数字相同的最长子序列长度

思路

  • 数组排序,要找的是 nums[i…j] 满足 nums[j] - nums[i] ≤ 2k 的最大长度

代码

class Solution {
public:
    int maximumBeauty(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int ans = 1;
        int i = 0;
        for (int j = 1; j < nums.size(); j++) {
            while (nums[j] - nums[i] > (2 *k)) i++;
            ans = max(ans, j - i + 1);
        }
        return ans;
    }
};