947. Lovely Permutation

Low-Budget Larry wants to impress a girl by gifting her a lovely permutation but with minimum amount of money.

Larry has a number k and an array of size n which is a permutation.

With one penny Larry can increase or decrease value of any element of the array by 1.

A lovely permutatation is a permutation where the element at ith index (consider 0 base indexing) should be in range of i - k to i + k ( i.e i - k <= arr[i] <= i + k for all i).

What is the minimum amount of money Larry would require to convert the given permutation into a lovely permutation?

Consider a penny to be a single unit of money.

A permutation of length n is an array consisting of n distinct integers from 0 to n - 1 in arbitrary order. 

For example, [1,2,0,4,3] is a permutation, but [0,1,1] is not a permutation (1 appears twice in the array), and [0,2,3] is also not a permutation because for n=3 the elements of permutation should be [0,1,2] but the array consist of 3.

Example 1:

Input : n = 4, k = 1, nums = [2, 1, 0, 3]

Output : 4

Explanation : One of the possible lovely permutation that requires minimum amount of pennies is:

1 0 2 3

4 pennies would be required to create this lovely permutation.

Example 2:

Input : n = 4, k = 1, nums = [2, 1, 3, 0]

Output : 4

Explanation : One of the possible lovely permutation that requires minimum amount of pennies is:

1 0 3 2

4 pennies would be required to create this lovely permutation.

Now Your Turn!

Pick the correct output for the given input

Input : n = 4, k = 1, nums = [3, 2, 1, 0]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= n <= 20
  • 0 <= k <= n
0
class Solution{
public:
long long int lovelyPermutation(int k,vector<int>& nums){
//your code goes here
}
};
Test Case

Input:

K
Nums