nikunjsoni

265

Aug 15th, 2021
1,112
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Solution {
  2. public:
  3.     int minCostII(vector<vector<int>>& costs) {
  4.         int k=costs[0].size(), n=costs.size(), firstMin, secondMin;
  5.        
  6.         for(int house=1; house<n; house++){
  7.             firstMin = secondMin = -1;
  8.             // Get the min and second min cost color in previous row.
  9.             for(int color=0; color<k; color++){
  10.                 int cost = costs[house-1][color];
  11.                 if(firstMin == -1 || cost < costs[house-1][firstMin]){
  12.                     secondMin = firstMin;
  13.                     firstMin = color;
  14.                 }
  15.                 else if(secondMin == -1 || cost < costs[house-1][secondMin]){
  16.                     secondMin = color;
  17.                 }
  18.             }
  19.            
  20.             // Calculate the cumulative cost for current row.
  21.             for(int color=0; color<k; color++){
  22.                 if(color == firstMin)
  23.                     costs[house][color] += costs[house-1][secondMin];
  24.                 else
  25.                     costs[house][color] += costs[house-1][firstMin];
  26.             }
  27.         }
  28.        
  29.         return *min_element(costs[n-1].begin(), costs[n-1].end());
  30.     }
  31. };
RAW Paste Data