
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- if nums[i]<=k, then
- return -1
Let us see the following implementation to get better understanding −
Example
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
Advertisements