Leetcode 3190: Find Minimum Operations to Make All Elements Divisible by Three

grid47
grid47
Exploring patterns and algorithms
Dec 24, 2023 4 min read

You are given an array of integers nums. In each operation, you can either add or subtract 1 from any element in nums. Your task is to determine the minimum number of operations required to make all elements of nums divisible by 3.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array `nums` containing `n` elements.
Example: Example 1: Input: nums = [2, 5, 8, 11] Output: 6 Explanation: You need 6 operations to make each number divisible by 3: subtract 1 from 2, subtract 1 from 5, subtract 1 from 8, and subtract 1 from 11.
Constraints:
• 1 <= nums.length <= 50
• 1 <= nums[i] <= 50
Output: Return the minimum number of operations to make all elements of `nums` divisible by 3.
Example: Example 2: Input: nums = [3, 6, 9] Output: 0 Explanation: All numbers are already divisible by 3, so no operations are needed.
Constraints:
• The result is a non-negative integer.
Goal: To find the minimum number of operations to make each number divisible by 3.
Steps:
• For each element in the array, calculate the remainder when divided by 3 (i.e., `num % 3`).
• If the remainder is 1, one operation is needed to either add or subtract 1 to make the number divisible by 3.
• If the remainder is 2, two operations are needed (either subtract 2 or add 1).
• Sum all the operations for the entire array and return the total.
Goal: The input array will always contain integers between 1 and 50, inclusive, and the length of the array will not exceed 50.
Steps:
• 1 <= nums.length <= 50
• 1 <= nums[i] <= 50
Assumptions:
• All array elements are between 1 and 50.
• The minimum number of operations will be calculated based on how much each element deviates from being divisible by 3.
Input: Example 1:
Explanation: For `nums = [2, 5, 8, 11]`, the remainders when divided by 3 are [2, 2, 2, 2]. Each element needs 2 operations (subtracting 1) to become divisible by 3. Therefore, the total number of operations is 2 + 2 + 2 + 2 = 8.

Input: Example 2:
Explanation: For `nums = [3, 6, 9]`, all elements are already divisible by 3. Thus, no operations are needed, and the result is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus