41.Cutting a Rod

Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces.Example

Example1

Input:[1, 5, 8, 9, 10, 17, 17, 20]
8
Output: 22

Explanation:
length   | 1   2   3   4   5   6   7   8  
--------------------------------------------
price    | 1   5   8   9  10  17  17  20
by cutting in two pieces of lengths 2 and 6

Example2

Input:[3, 5, 8, 9, 10, 17, 17, 20]
8

Output: 24

Explanation:
length   | 1   2   3   4   5   6   7   8  
--------------------------------------------
price    | 3   5   8   9  10  17  17  20
by cutting in eight pieces of length 1.

Solution: (Recursion)

class Solution
{
public:
    /**
     * @param prices: the prices
     * @param n: the length of rod
     * @return: the max value
     */
    int maxPrice = 0;
    void findPrice(vector<int> &prices, int n, int curPrice, vector<int> &dp)
    {

        if (n == 0)
        {
            maxPrice = max(maxPrice, curPrice);
            return;
        }

        if (n < 0)
        {
            return;
        }

        for (int i = 1; i <= n; i++)
        {
            findPrice(prices, n - i, curPrice + prices[i-1], dp);
        }

        return;
    }

    int cutting(vector<int> &prices, int n)
    {
        vector<int> dp(n + 1, -1);

        findPrice(prices, n, 0, dp);
        return maxPrice;
    }
};

Solution: (Recursion + Memo)

class Solution
{
public:
    /**
     * @param prices: the prices
     * @param n: the length of rod
     * @return: the max value
     */

    int findPrice(vector<int> &prices, int n, vector<int> &dp)
    {

        if (n <= 0)
        {
            return 0;
        }

        if (dp[n] != -1)
        {
            return dp[n];
        }

        int val = 0;
        for (int i = 1; i <= n; i++)
        {
            val = max(val, prices[i - 1] + findPrice(prices, n - i, dp));
        }

        dp[n] = val;
        return val;
    }

    int cutting(vector<int> &prices, int n)
    {
        vector<int> dp(n + 1, -1);

        int maxPrice = findPrice(prices, n, dp);
        return maxPrice;
    }
};

Solution: (Dp)

class Solution
{
public:
    /**
     * @param prices: the prices
     * @param n: the length of rod
     * @return: the max value
     */

    int cutting(vector<int> &prices, int n)
    {

        vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= n; j++)
            {

                if (i <= j)
                {
                    int inc = prices[i - 1] + dp[i][j - i];
                    int exc = dp[i - 1][j];
                    dp[i][j] = max(exc, inc);
                }
                else
                {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }

        return dp[n][n];
    }
};

Time Complexity: O(N^2)

Last updated