
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
Find Greatest Subarray of Given Length in Python
Suppose we have an array containing various integer values and a given length k. We have to find out the greatest subarray from the array of the given length. A subarray is said to be greater than another subarray, if subarray1[i] ≠ subarry2[i] and subarray1[i] > subarry2[i].
So, if the input is like nums = [5, 3, 7, 9], k = 2, then the output will be [7, 9].
To solve this, we will follow these steps −
- start := size of nums - k
- max_element := nums[start]
- max_index := start
- while start >= 0, do
- if nums[start] > max_element is non-zero, then
- max_element := nums[start]
- max_index := start
- return nums[from index max_index to max_index + k]
- if nums[start] > max_element is non-zero, then
- return nums[from index max_index to max_index + k]
Let us see the following implementation to get better understanding −
Example
def solve(nums, k): start = len(nums) - k max_element = nums[start] max_index = start while start >= 0: if nums[start] > max_element: max_element = nums[start] max_index = start start -= 1 return nums[max_index:max_index + k] print(solve([5, 3, 7, 9], 2))
Input
[5, 3, 7, 9], 2
Output
[7, 9]
Advertisements