Question: Programming Solve Later Description There is an array containing N natural numbers without duplicates. Change the position of two different elements by swap operation

Programming Solve Later Description There is an array containing N natural numbers

Programming Solve Later Description There is an array containing N natural numbers without duplicates. Change the position of two different elements by swap operation to make the difference of the elements adjacent to each other is K or less. However, you should use as few swap operations as possible An array, numbers is given as a parameter. Write a solution function which returns the minimum number of swaps needed to ensure that the difference between adjacent elements is less than or equal to K. Constraints 1 length of numbers 8 The element of numbers is a natural number. And all of them . are unique. 1 each element of numbers 100 S Javascript 1 function solution (numbers, K) { 2 3 4 } var answer = 0; return answer; 1 k 100 Return -1 when there is no way to make the difference between adjacent elements is less than or equal to K. Examples numbers [10, 40, 30, 20] [3, 7, 2, 8, 6, 4, 5, 1] Example #1 result 20 1 3 2 By changing the position of 30 and 40, the array becomes [10, 30, 40, 20]. Then the difference of adjacent elements becomes 20 or less. Example #2 By swapping the position of 3-4 and 2-5, the array becomes [4, 7, 5, 8, 6, 3, 2, 1]. Then the difference of adjacent elements becomes 3 or less. Result Result of [Run Test] or [Submit] will be displayed here

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock