CodeSprout程式萌芽
困難第 258 題 · 帳戶結餘
CodeSprout 官方2026/10/04 00:19
官方解答 · 置頂Java

官方解答|帳戶結餘

官方解答|帳戶結餘

解題思路

建立三個 Account,各以 0 為初值。按 commands 原順序執行,存款不收費。

以下 B 是本筆指令執行前的來源帳戶餘額,A 是指令要求的正整數金額,F = 0 是固定費用。『餘額足夠』是指足以支付要求金額及費用,即 B >= A + F;不能只比較 B 與 A。

本題採『不得透支;不足則整筆拒絕』,提領與轉帳都使用同一規則:

  1. B >= A + F:接受並完整執行要求金額 A,來源帳戶扣除 A + F。
  2. B < A + F:整筆拒絕,不扣金額、不扣費用,所有帳戶保持原狀。 不得縮減要求金額,也不得讓來源帳戶餘額變成負數。

接受提領時,來源帳戶扣除 A + F;接受轉帳時,先確認可支付 A + F,再一次更新兩個帳戶:來源扣除 A + F,下一帳戶只增加要求金額 A,費用不進入任何帳戶。 拒絕指令不計成功,並計一次失敗。存入一定成功且不收費;接受的提領、轉帳各算一次成功。金額必須為正整數,沒有只扣費用的零金額交易。

最後輸出帳號 0、1、2 的最後餘額。

正確性與邊界

例如,提款前餘額 5、要求提領 9、費用 0:因 5 < 9 + 0,整筆拒絕,餘額仍為 5。

空 commands 不執行交易,帳戶仍為初值,成功及失敗次數皆為 0。

複雜度

設 m 為指令數。時間 O(m),額外空間 O(1),固定三個帳戶及固定大小回傳。

公開範例

輸入 {"commands": [[0, 0, 5]]},依上述步驟得到 [5, 0, 0]。

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

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

import java.util.*;

public class Solution {
    private static class Account {
        private int balance;
        Account(int initial) { balance = initial; }
        void deposit(int amount) { balance += amount; }
        int withdraw(int amount) {
            if (balance < amount+0) return -1;
            balance -= amount+0;
            return amount;
        }
        int balance() { return balance; }
    }

    public static List<Integer> solve(int[][] commands) {
        Account[] accounts = { new Account(0), new Account(0), new Account(0) };
        int success = 0, failures = 0;
        List<Integer> result = new ArrayList<>();
        for (int[] command : commands) {
            int type = command[0], id = command[1], amount = command[2];
            boolean ok;
            if (type == 0) { accounts[id].deposit(amount); ok = true; }
            else {
                int transferred = accounts[id].withdraw(amount);
                ok = transferred != -1;
                if (ok && type == 2) accounts[(id+1)%3].deposit(transferred);
            }
            if (ok) success++; else failures++;
        }
        for (Account a : accounts) result.add(a.balance());
        return result;
    }
}

留言討論 0