We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find Maximum Non-decreasing Array Length

Difficulty: Hard


Problem Description

You are given a 0-indexed integer array nums. You can perform any number of operations, where each operation involves selecting a subarray of the array and replacing it with the sum of its elements. Return the maximum length of a non-decreasing array that can be made after applying operations.


Key Insights

  • A subarray is a contiguous non-empty sequence of elements within an array.
  • The goal is to maximize the length of a non-decreasing array by replacing subarrays with their sums.
  • If the array is already non-decreasing, the maximum length is the length of the array itself.
  • The problem can involve strategically choosing subarrays to maximize the length of the resulting non-decreasing structure.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve this problem, we can utilize a two-pointer technique to keep track of the current non-decreasing segment within the array. We iterate through the array and check if each element is non-decreasing compared to the previous one. If we encounter a decrease, we can consider replacing that segment with its sum to potentially create a longer non-decreasing segment. The maximum length of the non-decreasing segments encountered during this process will be our answer.


Code Solutions

def maxNonDecreasingLength(nums):
    n = len(nums)
    max_length = 1
    current_length = 1

    for i in range(1, n):
        if nums[i] >= nums[i - 1]:
            current_length += 1
        else:
            max_length = max(max_length, current_length)
            current_length = 1

    max_length = max(max_length, current_length)
    return max_length

# Example usage:
print(maxNonDecreasingLength([4, 3, 2, 6]))  # Output: 3
← Back to All Questions