700 · 杆子分割

描述

给一个 n 英寸长的杆子和一个包含所有小于 n 的尺寸的价格. 确定通过切割杆并销售碎片可获得的最大值.

 
样例

样例1

输入:
[1, 5, 8, 9, 10, 17, 17, 20]
8
输出:22
解释:
长度    | 1   2   3   4   5   6   7   8  
--------------------------------------------
价格    | 1   5   8   9  10  17  17  20
切成长度为 2 和 6 的两段。

样例2

输入:
[3, 5, 8, 9, 10, 17, 17, 20]
8
输出:24
解释:
长度    | 1   2   3   4   5   6   7   8  
--------------------------------------------
价格    | 3   5   8   9  10  17  17  20
切成长度为 1 的 8 段。

class Solution {
public:
    /**
     * @param prices: the prices
     * @param n: the length of rod
     * @return: the max value
     */
    int cutting(vector<int> &prices, int n) {
        // Write your code here
        int p_size = prices.size();
        vector<vector<int>>dp = vector<vector<int>>(p_size+1,vector<int>(n+1,0));
        for (int i = 1; i <= p_size;i++) {
            for (int j = 1; j <= n; j++) {
                if (j-i>=0) {
                    dp[i][j] =  max(dp[i-1][j],dp[i][j-i] + prices[i-1]);
                } else {
                    dp[i][j] = dp[i-1][j];
                }
            }
        }
        return dp[p_size][n];
    }
};

 

class Solution {
public:
    /**
     * @param prices: the prices
     * @param n: the length of rod
     * @return: the max value
     */
    int cutting(vector<int> &prices, int n) {
        // Write your code here
        int p_size = prices.size();
        vector<int> dp = vector<int>(n+1,0);

        for (int i = 1; i <= p_size;i++) {
            for (int j = 1; j <= n; j++) {
                if (j-i>=0) {
                    dp[j] =  max(dp[j],dp[j-i] + prices[i-1]);
                } else {
                    dp[j] = dp[j];
                }
            }
        }
        return dp[n];
    }
};

 

 
posted @ 2022-07-12 23:52  乐乐章  阅读(16)  评论(0编辑  收藏  举报