
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
Program to find longest equivalent sublist after K increments in Python
The longest equivalent sublist after K increments is known as the longest contiguous portion of a list where we can make all the elements equal by performing at most K increment operations.
Suppose we have a list of numbers called nums and k. Now, consider an operation where we can increment any one element once. If we can perform operations at most k times, we have to find the longest sub-list containing equal elements.
Input Output Scenario
Let's consider the following scenario, as we can increment 9 once and 6 four times to get the sublist [10, 10, 10], the length will be 3 -
Input: nums = [3, 5, 9, 6, 10, 7], k = 6, Output: 3
Longest Equivalent sub-list after K Increments
To find the longest sub-list where all elements can be made equal using at most K increments, first we have to sort the list. Next, we have to use a sliding window approach for maintaining a prefix sum.
At each step, we will check if the total number of increments required to make all numbers in the current window equal to the largest number is less than or equal to K. If it is equal, then we will update the maximum length.
Example 1
Following is the example which shows how to calculate the longest sub-list that can be made equivalent using at most K increments -
def longest_equal_sublist_after_k_increments(nums, k): nums.sort() left = 0 total = 0 max_len = 0 for right in range(len(nums)): total += nums[right] while nums[right] * (right - left + 1) - total > k: total -= nums[left] left += 1 max_len = max(max_len, right - left + 1) return max_len # Sample input list and K value numbers = [1, 2, 4] k = 5 print("Longest equivalent sub-list length after K increments:", longest_equal_sublist_after_k_increments(numbers, k))
Here is the output of the above example -
Longest equivalent sub-list length after K increments: 3
Example 2
Below is another example where we calculate the maximum number of elements that can be made equal with a limited number of increments -
def longest_equal_sublist_after_k_increments(nums, k): nums.sort() left = 0 total = 0 max_length = 0 for right in range(len(nums)): total += nums[right] while nums[right] * (right - left + 1) - total > k: total -= nums[left] left += 1 max_length = max(max_length, right - left + 1) return max_length # Sample input list and K value numbers = [3, 9, 6] k = 2 print("Longest equivalent sublist length after K increments:", longest_equal_sublist_after_k_increments(numbers, k))
Below is the output of the above example -
Longest equivalent sublist length after K increments: 1