clean c++ solution O(nk) time O(1) space with findMin()

  • -1
    class Solution {
        int minCostII(vector<vector<int>>& costs) {
            if (costs.empty() || costs[0].empty()) return 0;
            int n = costs.size();
            int k = costs[0].size();
            for (int i=1; i<n; ++i) {
                for (int j=0; j<k; ++j) {
                    costs[i][j] = costs[i][j] + findMin(costs, i-1, j);
            return findMin(costs, n-1, k+1);
        int findMin(vector<vector<int>>& costs, int i, int except) {
            int minCost = INT_MAX;
            for (int j=0; j<costs[i].size(); ++j) {
                if (j!=except) {
                    if (costs[i][j]<minCost)
                        minCost = costs[i][j];
            return minCost;

  • 0

    I don't think this is O(nk). Your findMin is O(k) and you have two more for loops outside findMin. This gives you a O(nk^2) complexity

Log in to reply

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