


The first line of input contains an integer T, the number
of test cases.
The first line of the test case contains a single integer
‘n’.
The second line contains ‘n’ space integers denoting the
elements of the array.
Return the minimum number of steps to convert it into
either a non-decreasing or non-increasing array
1<= T <=4
1<= n <=1000
1<= arr[i] <=1000
Where i varies from 1 to ‘n’.
Time Limit : 1 sec
The key idea is that the value of a modified array cannot be more than the maximum of the given array and cannot be less than the minimum of the given array. Hence we will consider every case for non-decreasing or non-increasing array separately. The one with minimum steps will be the answer.
In the First Approach, there are overlapping subcases. Hence we will use dynamic programming to optimize it. In case on non-increasing dp[i][j] represents to make first ‘i’ elements non-increasing when the ith element is ‘j’ and vice versa in non-decreasing.dp[i][j] equals to min(dp[i-1][k]+abs(arr[i]-’j’) where ‘k’ varies from ‘j’ to minimum.Similarly for non-decreasing ‘k’ varies from ‘j’ to maximum.