array and hashmap November 11, 2022

Removing minimum number of magic beans

Time O(nlog(n)) Space O(1) Open original problem

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)