Minimum Adjustment Cost

Description

Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater than a given number target.

If the array before adjustment is A, the array after adjustment is B, you should minimize the sum of |A[i]-B[i]|

You can assume each number in the array is a positive integer and not greater than 100.

Example

Example 1:
	Input:  [1,4,2,3], target=1
	Output:  2

Example 2:
	Input:  [3,5,4,7], target=2
	Output:  1

Thinking: f [i] [k] represents the number of the i becomes k, i before adjustment costs and the minimum number.
Enumeration of the i-1 is adjusted to a digital number j, i-th re-adjusted to enumerate K. Transfer do.

public class Solution {
    /**
     * @param A: An integer array.
     * @param target: An integer.
     */
    public int MinAdjustmentCost(ArrayList<Integer> A, int target) {
        // write your code here
        int n = A.size();
        int[][] f = new int[n + 1][101];
        for (int i = 0; i <= n ; ++i)
            for (int j = 0; j <=100; ++j)
                f[i][j] = Integer.MAX_VALUE;
        for (int i = 0; i <= 100; ++i)
            f[0][i] = 0;
        for (int i = 1; i <=n; ++i)
            for (int  j = 0; j <= 100;++j)
                if (f[i-1][j] != Integer.MAX_VALUE)
                for (int k = 0; k <= 100; ++k)
                    if (Math.abs(j-k) <= target)
                    if (f[i][k] > f[i-1][j] + Math.abs(A.get(i-1)-k))
                        f[i][k] = f[i-1][j] + Math.abs(A.get(i-1)-k);  
        int ans = Integer.MAX_VALUE;
        for (int i = 0; i <= 100; ++i)
            if (f[n][i] < ans)
                ans = f[n][i];
        return ans; 
    }
}

  

Guess you like

Origin www.cnblogs.com/FLAGyuri/p/12078447.html