• [LintCode] Minimum Adjustment Cost


    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 isB, you should minimize the sum of |A[i]-B[i]|

    Example

    Given [1,4,2,3] and target = 1, one of the solutions is [2,3,2,3], the adjustment cost is 2 and it's minimal.

    Return 2.

    Note

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

    动态规划,dp[i][j]表示把第i个数调整为j后的最小代价,状态转移方程为:

    dp[i][j] = min(dp[i][j], dp[i-1][k] + abs(A[i] - j));

    其中,k表示上一个数调整后的数值,范围在max(0, j - target) 与 min(100, j + target) 之间。

     1 class Solution {
     2 public:
     3     /**
     4      * @param A: An integer array.
     5      * @param target: An integer.
     6      */
     7     int MinAdjustmentCost(vector<int> A, int target) {
     8         // write your code here
     9         if (A.empty()) return 0;
    10         vector<vector<int>> dp(A.size(), vector<int>(101, INT_MAX));
    11         for (int i = 0; i <= 100; ++i) {
    12             dp[0][i] = abs(A[0] - i);
    13         }
    14         for (int i = 1; i < A.size(); ++i) {
    15             for (int j = 0; j <= 100; ++j) {
    16                 for (int k = max(0, j - target); k <= min(100, j + target); ++k)
    17                     dp[i][j] = min(dp[i][j], dp[i-1][k] + abs(A[i] - j));
    18             }
    19         }
    20         int res = INT_MAX;
    21         for (int i = 0; i <= 100; ++i) {
    22             res = min(res, dp[A.size()-1][i]);
    23         }
    24         return res;
    25     }
    26 };
  • 相关阅读:
    scrapy--Cookies
    python--signal
    python--redis
    TCP/IP 协议
    python--Wrapper
    python--inspect
    python--pexpect
    linux 特殊命令(一)
    day45 Pyhton 数据库Mysql 02
    day44 Pyhton 数据库Mysql
  • 原文地址:https://www.cnblogs.com/easonliu/p/4548865.html
Copyright © 2020-2023  润新知