Program to find minimum amount needed to be paid all good performers in Python

Suppose we have a list of performance ratings for coders. The manager wants to pay each coder at least Rs 1000, but if two coders are adjacent, the better performing coder must receive at least Rs 1000 more than the worse performing one. We need to find the minimum total amount required following these constraints.

So, if the input is like ratings = [1, 2, 5, 1], then the output will be 7000, as the minimum payment for each coder is [1000, 2000, 3000, 1000].

Algorithm

To solve this problem, we use a two-pass approach ?

  • Create a pay list with all values initialized to 1 (representing 1000 each)

  • Left to right pass: If current rating > previous rating, increase pay accordingly

  • Right to left pass: If current rating > next rating, ensure pay satisfies the constraint

  • Return the sum multiplied by 1000

Example

class Solution:
    def solve(self, ratings):
        pay = [1 for _ in ratings]
        
        # Left to right pass
        for i in range(1, len(ratings)):
            if ratings[i] > ratings[i-1]:
                pay[i] = pay[i-1] + 1
        
        # Right to left pass
        for i in range(len(ratings)-2, -1, -1):
            if ratings[i] > ratings[i+1]:
                pay[i] = max(pay[i], pay[i+1] + 1)
        
        return sum(pay) * 1000

# Test the solution
ob = Solution()
ratings = [1, 2, 5, 1]
result = ob.solve(ratings)
print(f"Ratings: {ratings}")
print(f"Minimum payment: Rs {result}")

# Let's also see the individual payments
pay = [1 for _ in ratings]
for i in range(1, len(ratings)):
    if ratings[i] > ratings[i-1]:
        pay[i] = pay[i-1] + 1

for i in range(len(ratings)-2, -1, -1):
    if ratings[i] > ratings[i+1]:
        pay[i] = max(pay[i], pay[i+1] + 1)

individual_payments = [p * 1000 for p in pay]
print(f"Individual payments: {individual_payments}")
Ratings: [1, 2, 5, 1]
Minimum payment: Rs 7000
Individual payments: [1000, 2000, 3000, 1000]

How It Works

The algorithm works in two phases ?

  1. Left-to-right pass: Ensures that if a coder has higher rating than the previous one, they get at least 1000 more

  2. Right-to-left pass: Ensures that if a coder has higher rating than the next one, they get at least 1000 more while maintaining the left-to-right constraint

Ratings: 1 2 5 1 Pay (×1000): 1 2 3 1 2>1 5>2 1<5 Total: 1+2+3+1 = 7 (×1000 = Rs 7000)

Conclusion

This two-pass algorithm ensures minimum payment while satisfying adjacency constraints. The left-to-right pass handles increasing sequences, while the right-to-left pass handles decreasing sequences, guaranteeing optimal solution.

Updated on: 2026-03-25T11:08:00+05:30

431 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements