Suppose two players are playing a game. Where several candies placed on a line, and person 1 is given a list of numbers called nums that is representing the point value of each candy. On each person's turn, they can pick 1, 2, or 3 candies from the front of the line, then delete them from list, and get the sum of their points added to their score. This game will end when all the candies are deleted and the person with the higher score will be the winner. We have to check person 1 can win this game or not.
So, if the input is like nums = [1, 1, 2, 3, 50], then the output will be True, as person 1 can take 1 candy, then the other player has to take 1, 2 or 3 candies. In any case, person 1 can take the candy with the value of 50.
To solve this, we will follow these steps −
n := size of nums
table := an array with three 0s.
for i in range n − 1 to 0, decrease by 1, do
profit := −inf
sum_val := 0
for j in range i to minimum of i + 3 and n, do
sum_val := sum_val + nums[j]
profit := maximum of profit and (sum_val − table[j − i])
set table := a list with three values [profit, table[0], table[1]]
return true when table[0] > 0, otherwise false
Let us see the following implementation to get better understanding −
Example
import math class Solution: def solve(self, nums): n = len(nums) table = [0, 0, 0] for i in range(n − 1, −1, −1): profit = −math.inf sum_val = 0 for j in range(i, min(i + 3, n)): sum_val += nums[j] profit = max(profit, sum_val − table[j − i]) table[:] = [profit, table[0], table[1]] return table[0] > 0 ob = Solution() nums = [1, 1, 2, 3, 50] print(ob.solve(nums))
Input
[1, 1, 2, 3, 50]
Output
True