CodeSprout程式萌芽
困難第 265 題 · 訂單總額
CodeSprout 官方2026/10/04 00:19
官方解答 · 置頂Java

官方解答|訂單總額

官方解答|訂單總額

解題思路

每列封裝為不可變 Item。類別 0 選 Discount,先算原小計再乘 75 整除 100;其餘選 Regular。每列分別取整,然後接著對數量大於0的列加2;數量0的列不加費,最後輸出[最後小計總和]。

正確性與邊界

取整發生在每列,不能先合計再折扣。後續費用依已折扣的小計與該列數量計算;最高列遇同分不覆寫較早索引。空資料的最高索引為 [],總額摘要為 0。

複雜度

設 n 為品項數。時間 O(n),額外空間 O(n)。

公開範例

輸入 {"items": [[1, 6, 2]]},依上述步驟得到 [14]。

下方程式可直接取代起始碼;使用 Java 11,入口為 Solution.solve。

CodeSprout 官方解答 · 題意分析、解題步驟與完整參考程式

import java.util.*;

public class Solution {
    private static class Item {
        final int category, price, quantity;
        Item(int[] row) { category=row[0]; price=row[1]; quantity=row[2]; }
        int original() { return price*quantity; }
    }
    private interface Pricing { int subtotal(Item item); }
    private static class Discount implements Pricing {
        public int subtotal(Item item) { return item.original()*75/100; }
    }
    private static class Regular implements Pricing {
        public int subtotal(Item item) { return item.original(); }
    }

    public static List<Integer> solve(int[][] items) {
        Pricing discount = new Discount(), regular = new Regular();
        List<Integer> values = new ArrayList<>();
        int originalTotal=0, finalTotal=0;
        int[] categoryTotals = new int[3];
        for (int[] row : items) {
            Item item = new Item(row);
            Pricing pricing = item.category == 0 ? discount : regular;
            int subtotal = pricing.subtotal(item);
            if (item.quantity > 0) subtotal += 2;
            originalTotal += item.original(); finalTotal += subtotal;
            categoryTotals[item.category] += subtotal;
            values.add(subtotal);
        }
        return Arrays.asList(finalTotal);
    }
}

留言討論 0