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

求将有序数组元素替换为X使数组和小于Y的最少替换数(优化O(n²)解法)

Hey there! Let's break down how to solve this problem way more efficiently than that O(n²) approach you've been working with. First, let's clarify the problem clearly:

Problem Statement

Given a sorted array A with N elements, plus two integers X and Y, find the minimum number of elements we need to replace with X so that the sum of A becomes less than Y.

What's Wrong with the Original O(n²) Code?

Your current code has two main issues:

  1. Inefficiency: It recalculates the entire array sum in every outer loop iteration, leading to O(n²) time complexity.
  2. Logical Flaw: It replaces the first i elements with X, but since the array is sorted, those are likely the smallest elements—replacing them does the least to reduce the total sum, meaning you'll end up needing more replacements than necessary.

Efficient O(n) Solution

Since the array is sorted, we can leverage this order to make optimal choices: to minimize the number of replacements, we should replace the largest elements first. Why? Because replacing a larger element with X will reduce the total sum by the maximum possible amount per replacement.

Here's the step-by-step approach:

  1. Calculate the original total sum of the array. If this sum is already less than Y, we don't need any replacements—return 0 immediately.
  2. Compute how much we need to reduce the sum: required_reduction = total_sum - Y + 1 (since we need the sum to be at most Y-1 to be less than Y).
  3. Traverse the array from the largest element to the smallest (assuming ascending order; reverse if it's descending):
    • For each element, calculate how much replacing it with X reduces the sum: delta = current_element - X.
    • If delta <= 0, replacing this element won't help (it will either increase the sum or leave it the same)—we can stop here, since all remaining elements will be smaller and also not useful.
    • Add delta to our total reduction count, increment the replacement count, and check if we've met or exceeded the required reduction. If yes, return the count.
  4. If we finish traversing all useful elements and still haven't met the required reduction, return -1 (meaning it's impossible to make the sum less than Y).

Code Implementation

def min_replacements(A, X, Y):
    total_sum = sum(A)
    if total_sum < Y:
        return 0
    
    required_reduction = total_sum - Y + 1
    replacements = 0
    total_reduction = 0
    
    # Traverse from largest to smallest (assuming ascending sorted array)
    for num in reversed(A):
        delta = num - X
        if delta <= 0:
            # No more useful elements to replace
            break
        total_reduction += delta
        replacements += 1
        if total_reduction >= required_reduction:
            return replacements
    
    # If we can't reduce enough even after replacing all possible elements
    return -1

Example Walkthrough

Let's test this with an example:

  • A = [1, 3, 5, 7] (ascending sorted), X = 2, Y = 10
  • Original sum: 1+3+5+7 = 16 which is >= 10
  • Required reduction: 16 - 10 + 1 = 7
  • Traverse reversed array:
    • Replace 7 with 2: delta = 5, total_reduction = 5 (still <7), replacements=1
    • Replace 5 with 2: delta=3, total_reduction=8 (>=7), replacements=2
  • Return 2—this is the minimum number of replacements needed, and the new sum is 1+3+2+2=8 <10, which is correct.

Why This Works

By targeting the largest elements first, we get the biggest possible reduction per replacement, ensuring we use the fewest number of changes to reach our goal. This approach runs in O(n) time (calculating the sum is O(n), traversing the array is O(n)) and uses O(1) extra space, which is a huge improvement over the original O(n²) solution.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:01:46