You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用递归求解仅含0和1数组的最长等数量子数组长度

Got it, let's work through this problem of writing a recursive function to find the longest subarray with equal numbers of 0s and 1s. Here's how I'd approach it:

Approach

First, let's break down the recursive logic. The core idea is to split the problem into smaller subproblems and combine their results:

  • Check if the current subarray (from start to end) has equal 0s and 1s. If yes, its length is a candidate for the maximum.
  • Recursively check the subarray that excludes the leftmost element (start+1 to end).
  • Recursively check the subarray that excludes the rightmost element (start to end-1).
  • The result for the current subarray is the maximum value from the three cases above.

We also need to handle base cases: if start >= end, return 0 (since a subarray of length 1 or empty can't have equal 0s and 1s).

Solution Code
def largestSubarray(A, start, end):
    # Base case: subarray length is 0 or 1, can't have equal 0s and 1s
    if start >= end:
        return 0
    
    # Count 0s and 1s in current subarray
    count0 = 0
    count1 = 0
    for i in range(start, end + 1):
        if A[i] == 0:
            count0 += 1
        else:
            count1 += 1
    
    current_length = end - start + 1 if count0 == count1 else 0
    
    # Recursive calls for subarrays excluding left and right ends
    left_result = largestSubarray(A, start + 1, end)
    right_result = largestSubarray(A, start, end - 1)
    
    # Return the maximum of the three possible values
    return max(current_length, left_result, right_result)
Explanation

Let's walk through the example you provided: A = [0,1,1,1,1,0,0,0,1], start=0, end=8:

  1. First, we count 0s and 1s in the entire array: 4 zeros and 5 ones, so current_length is 0.
  2. We recursively call largestSubarray(A, 0, 7): this subarray has 4 zeros and 4 ones, so current_length is 8.
  3. The recursive call largestSubarray(A, 1, 8) will return a value less than 8 (since the longest valid subarray here is shorter).
  4. The function returns the maximum of 0, 8, and the smaller value, so we get 8 as expected.

Notes

  • This recursive approach has a time complexity of O(n²) because each recursive call involves iterating through the current subarray to count 0s and 1s, and there are O(n²) total subarrays. For very large arrays, this might not be the most efficient, but it adheres strictly to the recursive requirement.
  • Make sure the input array only contains 0s and 1s as specified—if there are other values, you'd need to add validation, but the problem states the array is binary.

内容的提问来源于stack exchange,提问作者CChung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:06:58