Program to find maximum credit we can get by finishing some assignments in python

PythonServer Side ProgrammingProgramming

Suppose we have two lists of the same size, these are deadlines and credits and they are representing course assignments. Here deadlines[i] shows the deadline day for assignment i and credits[i] represents the amount of credits we get for assignment i. We have one day to complete an assignment, and can be completed before or on the deadline day. We cannot di multiple assignments at the same time. We have to find maximum credit we can gain by finishing some subset of assignments.

So, if the input is like deadlines = [1, 2, 2, 2] credits = [4, 5, 6, 7], then the output will be 18, as we can complete assignment with credit 5 at day 0, complete assignment with credit 6 at day 1 and complete assignment with credit 7 at day 3.

To solve this, we will follow these steps −

  • a := make a pair of deadlines and credits and sort them based on credits in descending order
  • if a is empty, then
    • return 0
  • res := a list of size (1 + maximum of deadlines) and fill with 0
  • ans := 0
  • for each pair (i, j) in a, do
    • for k in range i down to 0, decrease by 1, do
      • if res[k] is 0, then
        • res[k] := 1
        • ans := ans + j
        • come out from the loop
  • return ans

Let us see the following implementation to get better understanding −

Example 

Live Demo

class Solution:
   def solve(self, deadlines, credits):
      a = sorted(list(zip(deadlines, credits)), key=lambda x: x[1], reverse=True)
      if not a:
         return 0
      res = [0] * (max(deadlines) + 1)
      ans = 0
      for i, j in a:
         for k in range(i, -1, -1):
            if not res[k]:
               res[k] = 1
               ans += j
               break
      return ans
     
ob = Solution()
deadlines = [1, 2, 2, 2]
credits = [4, 5, 6, 7]
print(ob.solve(deadlines, credits))

Input

[1, 2, 2, 2], [4, 5, 6, 7]

Output

18
raja
Published on 02-Dec-2020 05:27:11
Advertisements