Program to find out the greatest subarray of a given length in python

PythonServer Side ProgrammingProgramming

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]
  • 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]
raja
Published on 04-Oct-2021 07:07:58
Advertisements