Program to Find Out the Points Achievable in a Contest in Python

PythonServer Side ProgrammingProgramming

Suppose we are in a programming contest where there are multiple problems but the contest ends when we solve one problem. Now if we have two lists of numbers of the same length called points, and chances. To explain it, here for the ith problem, we have a chances[i] percent chance of solving it for points[i] points. We also have another value k which represents the number of problems we can attempt. The same problem cannot be attempted twice.

If we devise an optimal strategy, we will have to find the expected value of the number of points we can get in the contest, which is rounded to the nearest integer. We can expect the value of attempting the ith problem as points[i] * chances[i] / 100.0, and this represents the number of points we would get on average.

So, if the input is like points= [600, 400, 1000], chances = [10, 90, 5], k = 2, then the output will be 392.

To solve this, we will follow these steps −

  • n := size of points

  • for i in range 0 to n, do

  • chances[i] := chances[i] / 100.0

  • R := arrange 0-3 sorted according to points descending

  • return int(dp(0, K))

  • Define a function dp() . This will take i, k

    • if i is same as n, then

      • return 0.0

    • j := R[i]

    • p := chances[j]

    • ev := p * points[j]

    • if k is same as 1, then

      • return maximum of ev, dp(i + 1, k)

    • return maximum of dp(i + 1, k - 1) *(1 - p) + ev, dp(i + 1, k)

Example 

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, points, chances, K):
      n = len(points)
      for i in range(n):
         chances[i] /= 100.0
      R = sorted(range(n), key=points.__getitem__, reverse=True)
      def dp(i, k):
         if i == n:
            return 0.0
         j = R[i]
         p = chances[j]
         ev = p * points[j]
         if k == 1:
            return max(ev, dp(i + 1, k))
         return max(dp(i + 1, k - 1) * (1 - p) + ev, dp(i + 1, k))
      return int(dp(0, K))

ob = Solution()
print (ob.solve([600, 400, 1000], [10, 90, 5], 2))

Input

[600, 400, 1000], [10, 90, 5], 2

Output

392
raja
Published on 23-Dec-2020 11:25:24
Advertisements