You're given an array nums which is a permutation of [0, 1, 2, ..., n - 1]. Your task is to find the optimal arrangement of indices that minimizes a special scoring function.
The score of any permutation perm is calculated as a circular sum:
score(perm) = |perm[0] - nums[perm[1]]| + |perm[1] - nums[perm[2]]| + ... + |perm[n-1] - nums[perm[0]]|
In other words, we're comparing each position in the permutation with the value at the next position (wrapping around to the beginning). Your goal is to find the permutation that minimizes this total cost.
If multiple permutations achieve the same minimum score, return the lexicographically smallest one. This is a classic optimization problem that combines graph theory with dynamic programming!
Input & Output
Visualization
Time & Space Complexity
For each of 2โฟ possible subsets and n positions, we try n transitions
DP table stores minimum cost for each (mask, position) pair
Constraints
- 1 โค nums.length โค 14
- nums is a permutation of [0, 1, 2, ..., n - 1]
- Time limit: 2 seconds per test case