
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
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
- Related Articles
- Longest Common Prefix in Python
- Python - Prefix sum list
- Implement Trie (Prefix Tree) in Python
- Prefix matching in Python using pytrie module
- Binary Prefix Divisible By 5 in Python
- Python – Substitute prefix part of List
- Python – Split Strings on Prefix Occurrence
- Prefix sum array in python using accumulate function
- K and -K in Python
- What does double underscore prefix do in Python variables?
- Program to perform prefix compression from two strings in Python
- Python Get the numeric prefix of given string
- Python - Add a prefix to column names in a Pandas DataFrame
- Program to find longest common prefix from list of strings in Python
- Check if suffix and prefix of a string are palindromes in Python

Advertisements