leetcode 2412. 完成所有交易的初始最少钱数

时间:2025-01-26 20:40:02

题目:2412. 完成所有交易的初始最少钱数 - 力扣(LeetCode)

题目要求的就是最差情况的本钱最少是多少,肯定是先亏钱再赚钱。

对于每个交易:

  • 如果是赚钱或保本,只有最大的本金对本钱有影响
  • 如果是亏钱,所有交易都影响本金
  • 如果全部交易都是亏钱的,最差情况下,最后一次交易的盈利应当最大

基于这些条件,可以简化计算方式:

class Solution {
public:
    long long minimumMoney(vector<vector<int>>& transactions) {
        long long ret = 0;
        int lc = 0;
        for (int i = 0; i < transactions.size(); i++) {
            vector<int>& t = transactions[i];
            if (t[0] > t[1]) {
                ret += t[0] - t[1];
            }
            if (t[0] > lc && t[1] > lc) {
                lc = min(t[0], t[1]);
            }
        }
        ret += lc;
        return ret;
    }
};