imashutosh51

Paint House II

Nov 8th, 2022 (edited)
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. '''
  2. Logic:
  3. Logic is same as paint house 1 but we need minimum from previous row but we can get the first and second minimum
  4. because if the minimum cost is of different color then cost to color is current_cost+previous min
  5.        else current_cost+second_previous_min;
  6. '''
  7. import math
  8. def paintCost(n, k, arr):
  9.     min_val = float('inf')
  10.     smin_val = float('inf')
  11.  
  12.     for j in range(k):
  13.         if arr[0][j] <= min_val:
  14.             smin_val = min_val
  15.             min_val = arr[0][j]
  16.  
  17.         elif arr[0][j] <= smin_val:
  18.             smin_val = arr[0][j]
  19.  
  20.     # process remaining rows
  21.     for i in range(1, n):
  22.  
  23.         cmin = float('inf')
  24.         csmin = float('inf')
  25.  
  26.         for j in range(k):
  27.  
  28.             if arr[i - 1][j] != min_val: #they can directly check is that min_val there or not, no need to store index.
  29.                 arr[i][j] += min_val
  30.             else:
  31.                 arr[i][j] += smin_val
  32.  
  33.             # update current min and second min
  34.             if arr[i][j] <= cmin:
  35.                 csmin = cmin
  36.                 cmin = arr[i][j]
  37.  
  38.             elif arr[i][j] <= csmin:
  39.                 csmin = arr[i][j]
  40.  
  41.         min_val = cmin
  42.         smin_val = csmin
  43.  
  44.     return min_val
Advertisement
Add Comment
Please, Sign In to add comment