Suppose we have an array nums and another value k. We have to check whether it is possible to reach the end of the array by performing these operations or not Operation: Traverse nums and, if any non-prime value is there then decrement the value of k by 1. Now if any value is prime then refill the value of k to its initial value.
So, if the input is like nums = [8, 5, 6, 7, 8], k = 2, then the output will be True as nums is not prime, then make k = 1, then nums is prime so k = 2, then nums is not prime so k = 1, again nums is prime so k = 2 and finally nums is not prime and k = 1 and we are at last index.
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
def isPrime(num): if num > 1: for i in range(2, num): if num % i == 0: return False return True return False def solve(arr,k): temp = k for i in range(len(arr)): if isPrime(arr[i]): k = temp else: k -= 1 if k <= 0 and i < (len(arr) - 1) and isPrime(arr[i + 1]) == False: return False return True nums = [8, 5, 6, 7, 8] k = 2 print(solve(nums, k))
[8, 5, 6, 7, 8], 2