内容中心

2026年知名的边缘计算数据采集网关优选公司推荐-深圳市中南新智造科技有限公司

To solve this problem, we need to find the maximum sum of any subarray with length at most (k). The solution leverages the prefix sum array and a deque to efficiently track the minimum prefix sum in a sliding window, leading to an optimal (O(n)) time complexity.

Approach

  1. Prefix Sum Array: Compute the prefix sum array where each element at index (i) represents the sum of the first (i) elements of the original array. This helps in quickly calculating the sum of any subarray.
  2. Deque for Sliding Window: Use a deque to maintain indices of the prefix sum array. The deque is kept in increasing order of the corresponding prefix sum values. This allows us to quickly access the minimum prefix sum in the valid window (subarrays of length at most (k)).
  3. Sliding Window: For each end of the prefix sum array:
    • Remove indices from the front of the deque if they are out of the valid window (i.e., older than (end - k)).
    • Calculate the current subarray sum using the minimum prefix sum from the deque.
    • Remove indices from the back of the deque if their corresponding prefix sum is greater than or equal to the current prefix sum (since they cannot be the minimum for future windows).
    • Add the current end index to the deque.

Solution Code

from collections import deque
from typing import List

def max_subarray_with_at_most_k_elements(nums: List[int], k: int) -> int:
    n = len(nums)
    prefix = [0] * (n + 1)
    for i in range(n):
        prefix[i + 1] = prefix[i] + nums[i]

    dq = deque()
    dq.append(0)
    max_sum = float('-inf')

    for end in range(1, n + 1):
        # Remove indices out of the window [end - k, end -1]
        while dq and dq[0] < end - k:
            dq.popleft()

        # Calculate current max sum for subarrays ending at end-1
        current_sum = prefix[end] - prefix[dq[0]]
        if current_sum > max_sum:
            max_sum = current_sum

        # Maintain deque in increasing order of prefix sums
        while dq and prefix[dq[-1]] >= prefix[end]:
            dq.pop()

        dq.append(end)

    return max_sum

Explanation

  • Prefix Sum: The prefix sum array allows us to compute the sum of any subarray from index (i) to (j) as (prefix[j+1] - prefix[i]).
  • Deque Usage: The deque maintains indices of the prefix sum array such that their values are increasing. This ensures that the front of the deque always gives the minimum prefix sum in the valid window, which is crucial for maximizing the subarray sum (since we subtract the minimum prefix sum from the current prefix sum).
  • Efficiency: Each element is added and removed from the deque at most once, leading to an (O(n)) time complexity. The space complexity is (O(n)) for the prefix sum array and deque.

This approach efficiently handles all cases, including negative numbers and subarrays of length up to (k), making it optimal for large input sizes.

深圳市中南新智造科技有限公司

深圳市中南新智造科技有限公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?