C++ concise and clean solution


  • 0
    D
    class Solution {
    public:
        int getMoneyAmount(int n) {
            vector<vector<int>> dp(n + 2, vector<int>(n + 2));
            for(int len = 2; len <= n; len++) {    //iterate through the length of the interval start from 2 because if len == 1, we need to pay 0, 
                for(int i = 1; i + len - 1 <= n; i++) {
                    int j = i + len - 1;
                    dp[i][j] = numeric_limits<int>::max();
                    for(int k = i; k <= j; k++) {  //select a number k in [i, j]
                        dp[i][j] = min(dp[i][j], k + max(dp[i][k - 1], dp[k + 1][j]));
                    }
                }
            }
            return dp[1][n];
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.