dp
with size n x (maxValue + 1)
where n
is the length of nums
and maxValue
is the maximum value in nums
.dp
with the cost to change nums[0]
to each possible value j
.i
from 1
to n-1
, iterate over all possible values j
from 0
to maxValue
.curmin
which represents the minimum cost to make the subarray nums[0...i-1]
non-decreasing with nums[i-1]
set to any value from 0
to j
.dp[i][j]
to curmin + abs(nums[i] - j)
.dp
for the non-decreasing case.nums
and iterating from n-1
to 0
.