You are given a bag that can hold at most maxWeight kg, and you have items represented by two 0-indexed integer arrays: price and weight. price[i] and weight[i] represent the price and weight of the ith item, respectively.
You are allowed to put any number of each item into the bag as long as the cumulative weight does not exceed maxWeight. Return the maximum total price of items you can put into the bag.
Example 1:
Input: price = [1,2,3], weight = [4,5,1], maxWeight = 15 Output: 42 Explanation: The maximum price can be obtained by putting: - 15 / 1 = 15 of the 3rd item which costs 15 * 3 = 45. Therefore the maximum price we can obtain is 45.
Example 2:
Input: price = [1,2,3], weight = [4,5,6], maxWeight = 15 Output: 6 Explanation: The maximum price can be obtained by putting: - 0 of the 1st item which costs 0 * 1 = 0. - 0 of the 2nd item which costs 0 * 2 = 0. - 2 of the 3rd item which costs 2 * 3 = 6. Therefore the maximum price we can obtain is 6.
Constraints:
1 <= price.length == weight.length <= 1051 <= price[i] <= 1031 <= weight[i] <= 1031 <= maxWeight <= 103When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The brute force approach to maximizing the price of items in a bag means we'll explore absolutely every possible combination of items. We check each combination to see if it fits within the bag's weight limit and then calculate the total price for that combination. Finally, we compare all the valid combinations to find the one with the highest total price.
Here's how the algorithm would work step-by-step:
def maximum_price_to_fill_bag_brute_force(
item_weights,
item_prices,
maximum_weight_of_bag
):
number_of_items = len(item_weights)
maximum_price_achieved = 0
# Iterate through all possible combinations of items
for i in range(1 << number_of_items):
current_weight = 0
current_price = 0
# Check each item to see if it's included in the current combination
for item_index in range(number_of_items):
if (i >> item_index) & 1:
# Add the item's weight and value to the current total
current_weight += item_weights[item_index]
current_price += item_prices[item_index]
# Check if the current combination is within the weight limit
if current_weight <= maximum_weight_of_bag:
# Update the maximum price if the current combination is more valuable
maximum_price_achieved = max(
maximum_price_achieved, current_price
)
return maximum_price_achieved
def main():
item_weights = [10, 20, 30]
item_prices = [60, 100, 120]
maximum_weight_of_bag = 50
result = maximum_price_to_fill_bag_brute_force(
item_weights,
item_prices,
maximum_weight_of_bag
)
print(f"Maximum price: {result}")
if __name__ == "__main__":
main()The goal is to maximize the total price of items we can fit into a bag with a weight limit. The optimal approach prioritizes items that give us the most value for their weight and uses only a fraction of any item if we can't fit the entire item.
Here's how the algorithm would work step-by-step:
def maximum_price_to_fill_bag(capacity, items):
# Calculate the value-to-weight ratio for each item
for item in items:
item['ratio'] = item['value'] / item['weight']
# Sort items based on value-to-weight ratio in descending order
items.sort(key=lambda item: item['ratio'], reverse=True)
total_value = 0.0
current_weight = 0.0
# Iterate through the sorted items
for item in items:
if current_weight + item['weight'] <= capacity:
# Add the entire item if it fits
current_weight += item['weight']
total_value += item['value']
else:
# Add a fraction of the item to fill the bag completely
remaining_capacity = capacity - current_weight
fraction = remaining_capacity / item['weight']
total_value += item['value'] * fraction
current_weight = capacity
break #Bag is full, no need to check the remaining items
return total_value| Case | How to Handle |
|---|---|
| prices or weights array is null or empty | Return 0 if either array is null or empty since there are no items to put in the bag. |
| bagWeight is 0 | Return 0 if bagWeight is 0 since nothing can be added to the bag. |
| prices or weights have negative values | Return an error or treat negative prices as 0 and negative weights as invalid and skip them. |
| prices or weights have zero values | Handle zero weights carefully to avoid division by zero errors, and zero prices should not negatively impact the result. |
| Very large bagWeight causing integer overflow | Use a data type that can handle larger numbers, such as long, for intermediate calculations to avoid overflow. |
| weights are all larger than bagWeight | Return 0 since no item can fit in the bag. |
| prices or weights array contain extremely large numbers | Use appropriate data types (e.g., long) and check for potential overflow or performance issues with large calculations. |
| prices and weights have mismatched lengths | Throw an IllegalArgumentException or return 0 if lengths are different, since you can't match prices with weights. |