Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int minCostII(vector<vector<int>>& costs) {
- int k=costs[0].size(), n=costs.size(), firstMin, secondMin;
- for(int house=1; house<n; house++){
- firstMin = secondMin = -1;
- // Get the min and second min cost color in previous row.
- for(int color=0; color<k; color++){
- int cost = costs[house-1][color];
- if(firstMin == -1 || cost < costs[house-1][firstMin]){
- secondMin = firstMin;
- firstMin = color;
- }
- else if(secondMin == -1 || cost < costs[house-1][secondMin]){
- secondMin = color;
- }
- }
- // Calculate the cumulative cost for current row.
- for(int color=0; color<k; color++){
- if(color == firstMin)
- costs[house][color] += costs[house-1][secondMin];
- else
- costs[house][color] += costs[house-1][firstMin];
- }
- }
- return *min_element(costs[n-1].begin(), costs[n-1].end());
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment