K Prefix in Python


Suppose we have a list of numbers nums and an integer k, we have to find the maximum possible i where nums[0] + nums[1] + ... + nums[i] ≤ k. We will return -1 if no valid i exists.

So, if the input is like nums = [4, -7, 5, 2, 6], k = 5, then the output will be 3, the index is 3 as if we add 4+(-7)+5+2 = 4, this is less than k, if we add last element it will no longer less than k, so the index is 3.

To solve this, we will follow these steps −

  • for i in range 1 to size of nums - 1, do
    • nums[i] := nums[i] + nums[i-1]
  • for i in range size of nums -1 to -1, decrease by 1, do
    • if nums[i]<=k, then
      • return i
  • return -1

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums, k):
      for i in range(1,len(nums)):
         nums[i]+=nums[i-1]
         for i in range(len(nums)-1,-1,-1):
            if nums[i]<=k:
                return i
      return -1
ob = Solution()
nums = [4, -7, 5, 2, 6]
k = 5
print(ob.solve(nums, k))

Input

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

Output

3

Updated on: 23-Sep-2020

368 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements