糖果优惠购买策略

158 阅读1分钟

我们需要计算购买所有糖果的最小花费。每种糖果的价格最初为2元,但如果购买数量达到某个阈值(数组 B 中的值),价格将降至1元。

数据结构选择

我们可以使用一个简单的循环来遍历每种糖果,并根据其需求量和打折阈值计算总花费。

算法步骤

  1. 初始化总花费为0。

  2. 遍历每种糖果:

    • 如果需求量 A[i] 小于等于打折阈值 B[i],则按原价2元计算。
    • 如果需求量 A[i] 大于打折阈值 B[i],则前 B[i] 个按2元计算,剩余的按1元计算。
  3. 返回总花费。

总结

这段代码通过遍历每种糖果的需求量和打折阈值,计算出购买所有糖果的最小花费。逻辑清晰,代码简洁,能够正确处理题目中的需求。 `import java.util.Arrays;

public class Main { public static int solution(int n, int[] A, int[] B) { int totalCost = 0;

    for (int i = 0; i < n; i++) {
        if (A[i] <= B[i]) {
            // 需求量小于等于打折阈值,按原价计算
            totalCost += A[i] * 2;
        } else {
            // 需求量大于打折阈值,前 B[i] 个按2元计算,剩余的按1元计算
            totalCost += B[i] * 2 + (A[i] - B[i]) * 1;
        }
    }
    
    return totalCost;
}

public static void main(String[] args) {
    System.out.println(solution(4, new int[]{2, 3, 2, 1}, new int[]{1, 3, 4, 1}) == 9);
    System.out.println(solution(5, new int[]{2, 2, 1, 2, 1}, new int[]{7, 8, 2, 4, 8}) == 12);
    System.out.println(solution(3, new int[]{3, 4, 1}, new int[]{2, 5, 1}) == 9);
}

}`