Program to find out the greatest subarray of a 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 at the first differing position, the first subarray has a larger element than the second subarray.

So, if the input is like nums = [5, 3, 7, 9], k = 2, then the output will be [7, 9].

Algorithm

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, then
      • max_element := nums[start]
      • max_index := start
    • start := start − 1
  • return nums[from index max_index to max_index + k]

Example

Let us see the following implementation to get better understanding ?

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]

# Test the function
nums = [5, 3, 7, 9]
k = 2
result = solve(nums, k)
print(f"Greatest subarray of length {k}: {result}")

The output of the above code is ?

Greatest subarray of length 2: [7, 9]

How It Works

The algorithm works by starting from the rightmost possible position where a subarray of length k can begin. It then moves leftward, comparing each potential starting element with the current maximum. When it finds a larger element, it updates both the maximum element and the starting index. This ensures we find the lexicographically largest subarray.

Another 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]

# Test with different examples
test_cases = [
    ([1, 4, 3, 7, 4, 9, 2, 5], 4),
    ([9, 8, 7, 6, 5], 3),
    ([1, 2, 3, 4], 2)
]

for nums, k in test_cases:
    result = solve(nums, k)
    print(f"Array: {nums}, k: {k} ? Greatest subarray: {result}")
Array: [1, 4, 3, 7, 4, 9, 2, 5], k: 4 ? Greatest subarray: [9, 2, 5]
Array: [9, 8, 7, 6, 5], k: 3 ? Greatest subarray: [9, 8, 7]
Array: [1, 2, 3, 4], k: 2 ? Greatest subarray: [3, 4]

Conclusion

This algorithm efficiently finds the lexicographically largest subarray of a given length by scanning from right to left and selecting the position with the maximum starting element. The time complexity is O(n) where n is the length of the array.

Updated on: 2026-03-26T13:43:54+05:30

726 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements