There was a thief, he has to pass through colored house - which can be red or blue, and contain 0 or more gems. The property of these gems is they multiply the previous gems by the current gems in the house. The houses are in array and thief can only visit once to steal the gems, with the goal of maximizing the gems. Find the range of house where he can maximize the gems in such a way that number of red houses are even.
Input: gems =[1,2,0,4,5,6,2,3], colors =[0,0,1,1,1,0,0,1]Output: 20Explanation: Red houses are with value 1. So, we take house 3 and 4, and hence color is4*5.
defmax_gems_with_even_reds(gems, colors):
n = len(gems)
max_product = float("-inf")
# Prefix and suffix products and red house counts prefix_product = [1] * (n +1)
prefix_reds = [0] * (n +1)
for i in range(n):
prefix_product[i +1] = (
prefix_product[i] * gems[i] if gems[i] !=0else1 )
prefix_reds[i +1] = prefix_reds[i] + (1if colors[i] ==1else0)
# Check different ranges to find the maximum product with even red house countfor i in range(n):
for j in range(i, n):
red_count = prefix_reds[j +1] - prefix_reds[i]
if red_count %2==0:
product =1for k in range(i, j +1):
if gems[k] !=0:
product *= gems[k]
if product > max_product:
max_product = product
return max_product
# Example usagegems = [1, 2, 0, 4, 5, 6, 2, 3]
colors = [0, 0, 1, 1, 1, 0, 0, 1]
print(max_gems_with_even_reds(gems, colors)) # Output: 20
⏰ Time complexity: O(n^2), because we have two nested loops to check all possible subarrays/ranges, and within those loops, we may compute the product which has O(n) complexity in the worst case.
🧺 Space complexity: O(n), due to the arrays used for prefix products and counts of red houses.