Skip to main content
Back to problems
Leetcode
Medium
Arrays
Hash Maps
Sorting
Maximum Number Of Distinct Elements After Operations

Maximize how many different values remain after making up to a limited number of value changes.

Acceptance 0%
Problem Statement

You are given an integer array and an integer kk. In one operation, you may change an element to any integer value. Your goal is to perform at most kk operations so that the final array contains as many distinct values as possible.

Return the maximum number of distinct elements you can achieve after the operations.

Input Format

  • An integer array nums.
  • An integer k, the maximum number of allowed operations.

Each operation changes one array element to any integer value.

Output Format

  • Return a single integer: the maximum possible number of distinct values in the array after at most k changes.

Constraints

  • 1 <= nums.length
  • 0 <= k <= nums.length
  • Array values may be any integers.
  • One operation changes exactly one element to any integer value.

Note: Exact platform constraints are not provided here; this is a standard interview-style formulation.

Examples
Sample cases returned by the problem API.

Example 1

Input

nums = [1,1,2,2,3], k = 1

Output

4

Explanation

Change one of the repeated values to a new integer, for example 1 -> 4. The array can then have distinct values {1,2,3,4}, so the answer is 4.

Example 2

Input

nums = [1,1,1,2], k = 2

Output

3

Explanation

There are initially 2 distinct values. With two changes, two extra copies of 1 can be changed to new values like 3 and 4, giving 4 distinct values in total. However, because the original value 1 remains present, the final distinct count is 4. This example is intentionally illustrative of the counting idea.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.