Talentd
FleetCode

4053. Minimum Operations to Make Every Element Palindromic

Medium15.5% acceptance

You are given an integer array nums.

In one operation, you may choose an index i and either increment or decrement nums[i] by 2.

Return the minimum number of operations required to make every element in nums a positive palindrome. Different elements may be changed into different palindromic integers.

Example 1:

Input: nums = [10,12,14,16]

Output: 9

Explanation:

One optimal sequence of operations is:

  • Decrement nums[0] by 2 once to change it from 10 to 8.
  • Decrement nums[1] by 2 twice to change it from 12 to 8.
  • Decrement nums[2] by 2 three times to change it from 14 to 8.
  • Increment nums[3] by 2 three times to change it from 16 to 22.

After 1 + 2 + 3 + 3 = 9 operations, nums = [8, 8, 8, 22], and every element is a positive palindromic integer.

It can be shown that fewer than 9 operations cannot achieve this.

Example 2:

Input: nums = [9,10,11,10]

Output: 2

Explanation:

Decrement nums[1] and nums[3] by 2 once each.

After 2 operations, nums = [9, 8, 11, 8], and every element is a positive palindromic integer.

At least one operation is needed for each of these two elements, so the minimum number of operations is 2.

Example 3:

Input: nums = [125]

Output: 2

Explanation:

Decrement nums[0] by 2 twice to change it from 125 to 121, which is a positive palindromic integer.

A single operation would change it to 123 or 127, neither of which is palindromic. Thus, the minimum number of operations is 2.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109

Hints open one at a time

Hint 1

Each operation preserves parity. Handle each element independently by finding its nearest positive palindrome of the same parity.

Hint 2

Precompute all positive palindromes up to 2,000,000,002 by mirroring their first halves, and separate them into sorted lists by parity. Perform this precomputation only once, using global or static initialization, and reuse the lists across all test cases.

Hint 3

Binary search the appropriate list for the closest candidates on either side of each element. Changing x into p costs |x - p| / 2 operations.

21:06
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def minOperations(self, nums: list[int]) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[10,12,14,16]
Input
[9,10,11,10]
Input
[125]
Your code is saved on this device.Solution