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

Suppose we have given a list of numbers called ratings, and this is showing the performance scores of coders. Now the manager wants to give Rs 1000 to every coder except if two coders are adjacent, they would like to pay the better performing coder at least Rs 1000 higher than the worse performing one. We have to find the minimum amount the manager can pay following above constraints.

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

To solve this, we will follow these steps −

  • pay:= a list of size same as ratings, initially all values are 1

  • for i in range 1 to size of ratings - 1, do

    • if ratings[i] > ratings[i-1], then

      • pay[i] := pay[i-1]+1

  • for i in range size of ratings -2 to 0, decrease by 1, do

    • if ratings[i] > ratings[i+1], then

      • pay[i] := maximum of pay[i] and pay[i+1]+1

  • return (sum of the elements of pay) *1000

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, ratings):
      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)
      return sum(pay)*1000
ob = Solution()
ratings = [1, 2, 5, 1]


[1, 2, 5, 1]