Talentd
FleetCode

3149. Find the Minimum Cost Array Permutation

Hard26.1% acceptance1 company

You are given an array nums which is a permutation of [0, 1, 2, ..., n - 1]. The score of any permutation of [0, 1, 2, ..., n - 1] named perm is defined as:

score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n - 1] - nums[perm[0]]|

Return the permutation perm which has the minimum possible score. If multiple permutations exist with this score, return the one that is lexicographically smallest among them.

Example 1:

Input: nums = [1,0,2]

Output: [0,1,2]

Explanation:

The lexicographically smallest permutation with minimum cost is [0,1,2]. The cost of this permutation is |0 - 0| + |1 - 2| + |2 - 1| = 2.

Example 2:

Input: nums = [0,2,1]

Output: [0,2,1]

Explanation:

The lexicographically smallest permutation with minimum cost is [0,2,1]. The cost of this permutation is |0 - 1| + |2 - 2| + |1 - 0| = 2.

Constraints:

  • 2 <= n == nums.length <= 14
  • nums is a permutation of [0, 1, 2, ..., n - 1].

Asked at 1 company

Hints open one at a time

Hint 1
The score function is cyclic, so we can always set perm[0] = 0 for the smallest lexical order.
Hint 2
It’s similar to the Traveling Salesman Problem. Use Dynamic Programming.
Hint 3
Use a bitmask to track which elements have been assigned to perm.
34:32
Still stuck?Read 5 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def findPermutation(self, nums: List[int]) -> List[int]:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,0,2]
Input
[0,2,1]
Your code is saved on this device.Solution