Sell Diminishing-Valued Colored Balls

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
class Solution:
    def maxProfit(self, inventory: List[int], orders: int) -> int:
        MOD = 10**9 + 7

        # Sorting the inventory in descending order
        inventory.sort(reverse=True)

        # Adding a 0 at the end to simplify the loop
        inventory.append(0)

        result = 0
        k = 1

        # Looping through the inventory
        for i in range(len(inventory) - 1):
            # If there's a difference between two adjacent elements and there are remaining orders
            if inventory[i] > inventory[i + 1] and orders > 0:
                # Determine how many balls can be sold at the current value
                count = (inventory[i] - inventory[i + 1]) * k

                # If the count is less than the remaining orders
                if orders >= count:
                    # Sum the arithmetic series from inventory[i + 1] + 1 to inventory[i]
                    result += (inventory[i] + inventory[i + 1] + 1) * (inventory[i] - inventory[i + 1]) // 2 * k
                    orders -= count
                else:
                    # If the remaining orders are less than the count, we calculate how many full cycles we can make and the remainder
                    full_cycles = orders // k
                    remainder = orders % k

                    # Sum the arithmetic series for the full cycles
                    result += (inventory[i] + inventory[i] - full_cycles + 1) * full_cycles // 2 * k

                    # Add the remainder
                    result += (inventory[i] - full_cycles) * remainder
                    orders = 0

                result %= MOD

            # If no remaining orders, break the loop
            if orders == 0:
                break

            k += 1

        return result