Minimum Operations to Make Array Sum Divisible by K - Problem
You're given an integer array nums and an integer k. Your goal is to make the sum of all elements in the array divisible by k using the minimum number of operations.
Operation: Select any index i and replace nums[i] with nums[i] - 1 (decrease by 1).
What's the minimum number of operations needed?
Example: If nums = [1, 2, 3] and k = 3, the sum is 6, which is already divisible by 3, so we need 0 operations. But if nums = [1, 2, 4] and k = 3, the sum is 7. We need to reduce it by 1 to make it 6 (divisible by 3), so the answer is 1.
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1, 2, 3], k = 3
โบ
Output:
0
๐ก Note:
Sum = 6, which is already divisible by 3 (6 % 3 = 0), so no operations needed.
example_2.py โ Single Operation
$
Input:
nums = [1, 2, 4], k = 3
โบ
Output:
1
๐ก Note:
Sum = 7, and 7 % 3 = 1. We need 1 operation to make it 6, which is divisible by 3.
example_3.py โ Multiple Operations
$
Input:
nums = [5, 6, 7], k = 4
โบ
Output:
2
๐ก Note:
Sum = 18, and 18 % 4 = 2. We need 2 operations to make it 16, which is divisible by 4.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 106
- 1 โค k โค 106
- Important: We can only decrease elements, never increase them
Visualization
Tap to expand
Understanding the Visualization
1
Find Current Position
Calculate sum of array elements
2
Find Target
Locate nearest smaller multiple of k
3
Calculate Gap
The gap is sum % k operations
4
Minimize Steps
Each operation reduces sum by 1
Key Takeaway
๐ฏ Key Insight: The remainder when dividing the sum by k tells us exactly how many steps we need to 'walk backwards' to reach divisibility!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code