- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 max values of sublists of size k in Python
Suppose we have a list nums and another value k, we have to find the maximum values of each sublist of size k.
So, if the input is like nums = [12, 7, 3, 9, 10, 9] k = 3, then the output will be [12, 9, 10, 10]
To solve this, we will follow these steps −
if k > size of nums, then
return a blank list
res := a new list
temp := nums[0]
temp := npoint := 0
for i in range 0 to k − 1, do
if nums[i] > temp, then
temp := nums[i]
point := i
insert temp at the end of res
for i in range k to size of nums, do
if nums[i] < temp and (i − point) < k, then
temp := nums[point]
otherwise when nums[i] < temp and (i − point) >= k, then
point := i − k + 1
for j in range i − k + 1 to i, do
if nums[j] > nums[point], then
point := j
temp := nums[point]
otherwise,
temp := nums[i]
point := i
insert temp at the end of res
return res
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums, k): if k > len(nums): return [] res = [] temp = nums[0] point = 0 for i in range(k): if nums[i] > temp: temp = nums[i] point = i res.append(temp) for i in range(k, len(nums)): if nums[i] < temp and (i − point) < k: temp = nums[point] elif nums[i] < temp and (i − point) >= k: point = i − k + 1 for j in range(i − k + 1, i + 1): if nums[j] > nums[point]: point = j temp = nums[point] else: temp = nums[i] point = i res.append(temp) return res ob = Solution() nums = [12, 7, 3, 9, 10, 9] k = 3 print(ob.solve(nums, k))
Input
[12, 7, 3, 9, 10, 9], 3
Output
[12, 9, 10, 10]