LeetCode 题解工作台
完成所有交易的初始最少钱数
给你一个下标从 0 开始的二维整数数组 transactions ,其中 transactions[i] = [cost i , cashback i ] 。 数组描述了若干笔交易。其中每笔交易必须以 某种顺序 恰好完成一次。在任意一个时刻,你有一定数目的钱 money ,为了完成交易 i , mo…
3
题型
7
代码语言
3
相关题
当前训练重点
困难 · 贪心·invariant
答案摘要
我们先累计所有负收益,记为 。然后枚举每个交易 $\text{transactions}[i] = [a, b]$ 作为最后一个交易,如果 $a > b$,说明当前的交易是亏钱的,而这个交易在此前我们累计负收益的时候,已经被计算,因此取 $s + b$ 更新答案;否则,取 $s + a$ 更新答案。 时间复杂度 ,其中 为交易数。空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路
题目描述
给你一个下标从 0 开始的二维整数数组 transactions,其中transactions[i] = [costi, cashbacki] 。
数组描述了若干笔交易。其中每笔交易必须以 某种顺序 恰好完成一次。在任意一个时刻,你有一定数目的钱 money ,为了完成交易 i ,money >= costi 这个条件必须为真。执行交易后,你的钱数 money 变成 money - costi + cashbacki 。
请你返回 任意一种 交易顺序下,你都能完成所有交易的最少钱数 money 是多少。
示例 1:
输入:transactions = [[2,1],[5,0],[4,2]] 输出:10 解释: 刚开始 money = 10 ,交易可以以任意顺序进行。 可以证明如果 money < 10 ,那么某些交易无法进行。
示例 2:
输入:transactions = [[3,0],[0,3]] 输出:3 解释: - 如果交易执行的顺序是 [[3,0],[0,3]] ,完成所有交易需要的最少钱数是 3 。 - 如果交易执行的顺序是 [[0,3],[3,0]] ,完成所有交易需要的最少钱数是 0 。 所以,刚开始钱数为 3 ,任意顺序下交易都可以全部完成。
提示:
1 <= transactions.length <= 105transactions[i].length == 20 <= costi, cashbacki <= 109
解题思路
方法一:贪心
我们先累计所有负收益,记为 。然后枚举每个交易 作为最后一个交易,如果 ,说明当前的交易是亏钱的,而这个交易在此前我们累计负收益的时候,已经被计算,因此取 更新答案;否则,取 更新答案。
时间复杂度 ,其中 为交易数。空间复杂度 。
class Solution:
def minimumMoney(self, transactions: List[List[int]]) -> int:
s = sum(max(0, a - b) for a, b in transactions)
ans = 0
for a, b in transactions:
if a > b:
ans = max(ans, s + b)
else:
ans = max(ans, s + a)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(n), where n is the number of transactions, as we iterate through the list once to categorize and calculate the required money. Space complexity is O(1) because we only store a few variables to track the maximum deficit and the total cost of transactions with cashback greater than or equal to the cost. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates understanding of greedy algorithms and how to apply them to financial transaction problems.
- question_mark
Candidate is able to identify the need for categorizing transactions based on cashback and cost.
- question_mark
Candidate can efficiently handle the two categories of transactions and track the maximum deficit to calculate the required money.
常见陷阱
外企场景- error
Not properly categorizing transactions based on cashback vs cost, leading to incorrect results.
- error
Failing to track the maximum deficit across transactions where cashback is less than cost.
- error
Overcomplicating the problem by trying to consider transaction order beyond the greedy approach.
进阶变体
外企场景- arrow_right_alt
Consider how the problem would change if there were different transaction types with additional constraints.
- arrow_right_alt
How would the solution change if you were allowed to reorder the transactions yourself before processing?
- arrow_right_alt
What if the problem involved adding more types of transaction attributes, such as interest rates or transaction fees?