Solution 2 for Scaler Topics Fortnightly Contest - 13
Learn via video course

DSA Problem Solving for Interviews using Java
by Jitender Punia
1000
4.9
This article is part of the Scaler Topics Fortnightly Contest - 13
Solution Approach
- As the cost is the sum of absolute difference of adjacent elements.
- So, the cost will be minimum if the array is in increasing or decreasing order. Both of them will give minimum cost. And both of the array will be beautiful.
- So, we have to just find the minimum number of swaps required to make array increasing or decreasing.
Time Complexity - O(nlogn)
Space Complexity - O(n)