C# Fast solution O(nk) time, O(1) space


  • 0
    G
    public class Solution {
    public int MinCostII(int[,] costs) {
        var n = costs.GetLength(0);
        var k = costs.GetLength(1);
        
        if(n == 0) { return 0; }
        if(n>1 && k == 1){ return int.MaxValue;}
        
        var pTot= 0; var pTotI =-1;
        var pTot2 = 0; 
        
        var min = int.MaxValue; var minI = -1;
        var min2 = int.MaxValue; 
        
        var total =0;
        
        for(int i = 0; i<n; i++){
            for(int j = 0; j <k; j++){
                var c = costs[i,j];
                var nc = c;
                
                if(j == pTotI){ nc += pTot2; } 
                else{ nc += pTot;}
                
                if(nc<min){ min2 = min; min = nc; minI = j;}
                else if(nc<min2){min2 = nc; }
            }
            
            pTot = min; pTotI = minI;
            pTot2 = min2;
            
            min = int.MaxValue; minI = -1;
            min2 = int.MaxValue;
            
        }
        
        return pTot;
    }
    

    }


Log in to reply
 

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