classSolution{public:intminCostII(vector<vector<int>>&costs){intprevIndex=-1;// The previous minimum indexintprevMin1=0;// Minimum cost so farintprevMin2=0;// 2nd minimum cost so farfor(constvector<int>&cost:costs){// O(n)intindex=-1;// The painted index s.t. achieve the minimum cost after// Painting current houseintmin1=INT_MAX;// The minimum cost after painting current houseintmin2=INT_MAX;// The 2nd minimum cost after painting current housefor(inti=0;i<cost.size();++i){// O(k)constinttheCost=cost[i]+(i==prevIndex?prevMin2:prevMin1);if(theCost<min1){index=i;min2=min1;min1=theCost;}elseif(theCost<min2){// Min1 <= theCost < min2min2=theCost;}}prevIndex=index;prevMin1=min1;prevMin2=min2;}returnprevMin1;}};
classSolution{publicintminCostII(int[][]costs){intprevIndex=-1;// The previous minimum indexintprevMin1=0;// Minimum cost so farintprevMin2=0;// 2nd minimum cost so farfor(int[]cost:costs){// O(n)// The painted index s.t. achieve the minimum cost after painting current houseintindex=-1;intmin1=Integer.MAX_VALUE;// The minimum cost after painting current houseintmin2=Integer.MAX_VALUE;// The 2nd minimum cost after painting current housefor(inti=0;i<cost.length;++i){// O(k)finalinttheCost=cost[i]+(i==prevIndex?prevMin2:prevMin1);if(theCost<min1){index=i;min2=min1;min1=theCost;}elseif(theCost<min2){// Min1 <= theCost < min2min2=theCost;}}prevIndex=index;prevMin1=min1;prevMin2=min2;}returnprevMin1;}}
classSolution:defminCostII(self,costs:List[List[int]])->int:prevIndex=-1# The previous minimum indexprevMin1=0# Minimum cost so farprevMin2=0# 2nd minimum cost so farforcostincosts:# O(n)index=-1# The painted index s.t. achieve the minimum cost after painting current housemin1=math.inf# The minimum cost after painting current housemin2=math.inf# The 2nd minimum cost after painting current housefori,cstinenumerate(cost):# O(k)theCost=cst+(prevMin2ifi==prevIndexelseprevMin1)iftheCost<min1:index=imin2=min1min1=theCosteliftheCost<min2:# Min1 <= theCost < min2min2=theCostprevIndex=indexprevMin1=min1prevMin2=min2returnprevMin1