Minimum Operations to Make Array Sum Divisible by K

You are given an integer array `nums` and an integer `k`. In one operation you may pick any index `i` and replace `nums[i]` with `nums[i] - 1`. Return the **minimum** number of operations needed to make the sum of the array divisible by `k`.

30:00

Minimum Operations to Make Array Sum Divisible by K
easy
Free written solution
Topics
Companies

You are given an integer array nums and an integer k. In one operation you may pick any index i and replace nums[i] with nums[i] - 1.

Return the minimum number of operations needed to make the sum of the array divisible by k.

Example 1:
Input: {"nums":[3,9,7],"k":5}
Output: 4
Constraints:
  • 1≤nums.length≤10001 \leq nums.length \leq 1000

  • 1≤nums[i]≤10001 \leq nums[i] \leq 1000

  • 1≤k≤1001 \leq k \leq 100

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[3,9,7],"k":5}

Each operation lowers the array sum by exactly 1, no matter which element it touches. So only the total matters: add it up first.

nums (0 of 3 added)

3
9
7

total

0

once the total is known, place it between two multiples of k = 5

Variables
VariableValue
k5
total0
DepthFunction Call
Stack empty
0/9