题解 | #相差不超过k的最多数#
相差不超过k的最多数
https://www.nowcoder.com/practice/562630ca90ac40ce89443c91060574c6
def max_numbers_with_difference_k(nums, k): nums.sort() # 先对数组进行排序 count = 1 left, right = 0, 1 while right < len(nums): # 判断右边界元素与左边界元素的差值是否超过 k if nums[right] - nums[left] <= k: # 没超过 k,则右边界右移 right += 1 # 更新最大选择数目的记录 count = max(count, right - left) else: # 超过了 k,则左边界右移 left += 1 return count # 示例调用 n, k = map(int, input().split()) nums = list(map(int, input().split())) print(max_numbers_with_difference_k(nums, k))