Removing minimum number of magic beans

November 11, 2022

array-and-hashmap

Problem URL: Removing minimum number of magic beans

We will sort the beans. Then for each element, we will take the totalSum-((arrLen-currIdx)*currNum) and take the minimum of all such values.

class Solution:
    def minimumRemoval(self, beans: List[int]) -> int:
        beans.sort()
        total = sum(beans)
        length = len(beans)

        remove = math.inf
        for i, bean in enumerate(beans):
            remove = min(remove, total-(length-i)*bean)
        return remove

Time Complexity: O(nlog(n))
Space Complexity: O(1)