Maximize distinct values after unique ± offsets
xAISoftware Engineer · Technical ScreenLast updated
This problem tests greedy strategy and sorting to determine the maximum possible count of distinct values in an array after applying exactly one offset from a given set of allowed integers to each element.
Problem Statement
You are given an array of integers nums and a set of distinct integer offsets offsets. You must assign exactly one value from offsets to each element in nums such that the resulting array transformed has the maximum possible number of distinct values.
Specifically, for each index i from 0 to n-1, you choose an offset k from offsets and define transformed[i] = nums[i] + k. Note that you cannot use the same offset index for multiple positions; however, the problem states you have an infinite supply of the values in offsets to choose from for each position. Wait—to clarify: you may pick any k from offsets for each nums[i] independently. The goal is to maximize the number of unique values in the resulting array.
Function Signature
def max_distinct_values(nums: List[int], offsets: List[int]) -> int:
Constraints
1 <= len(nums) <= 10^51 <= len(offsets) <= 100-10^9 <= nums[i], offsets[i] <= 10^9
Examples
Example 1:
Input: nums = [1, 2, 3], offsets = [0, 10]
Output: 3
Explanation: We can choose 1+0=1, 2+10=12, 3+0=3. The set is {1, 12, 3}, size 3.
Example 2:
Input: nums = [1, 1, 1], offsets = [0, 1]
Output: 2
Explanation: We can choose 1+0=1 and 1+1=2. The set is {1, 2}.
Hints
Hint 1
Consider the perspective of how many elements can map to the same target value.
Hint 2
If many elements in 'nums' share the same value, how many distinct values can they possibly produce given the number of offsets?
Hint 3
Sort the 'nums' array and group identical values; for each unique value in 'nums', you can distribute its occurrences across the available offsets.
Follow-up questions
- What if each offset in 'offsets' can only be used a limited number of times?
- How does the complexity change if we want to minimize the number of distinct values instead?
- Can this be solved using a max-flow min-cost algorithm if constraints on offset usage were introduced?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.