← Static tasks

714. Best Time to Buy and Sell Stock with Transaction Fee

leetcode medium

#array#csharp#leetcode#math#medium

Task

Вам дан массив prices, где prices[i] - это цена данной акции в i-й день, и целое число fee, представляющее собой комиссию за сделку. Найдите максимальную прибыль, которую вы можете получить. Вы можете совершить сколько угодно сделок, но за каждую сделку вам придется заплатить комиссию. Примечание: Вы не можете совершать несколько сделок одновременно (то есть вы должны продать акции, прежде чем купить их снова). Комиссия за сделку взимается только один раз за каждую покупку и продажу акций.

Пример:

Input: prices = [1,3,2,8,4,9], fee = 2

Output: 8

C# solution

matched/original
public class Solution {
    public int MaxProfit(int[] prices, int fee) {
        int cash = 0, hold = -prices[0];
        foreach (int price in prices) {
            cash = Math.Max(cash, hold + price - fee);
            hold = Math.Max(hold, cash - price);
        }
        return cash;
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public int MaxProfit(vector<int>& prices, int fee) {
        int cash = 0, hold = -prices[0];
        foreach (int price in prices) {
            cash = max(cash, hold + price - fee);
            hold = max(hold, cash - price);
        }
        return cash;
    }
}

Java solution

matched/original
public class Solution {
    public int maxProfit(int[] prices, int fee) {
        int cash = 0, hold = -prices[0];
        for (int price : prices) {
            cash = Math.max(cash, hold + price - fee);
            hold = Math.max(hold, cash - price);
        }
        return cash;
    }
}

JavaScript solution

matched/original
var maxProfit = function(prices, fee) {
    let cash = 0, hold = -prices[0];
    for (let price of prices) {
        cash = Math.max(cash, hold + price - fee);
        hold = Math.max(hold, cash - price);
    }
    return cash;
};

Python solution

matched/original
def maxProfit(prices, fee):
    cash, hold = 0, -prices[0]
    for price in prices:
        cash = max(cash, hold + price - fee)
        hold = max(hold, cash - price)
    return cash

Go solution

matched/original
package main

func maxProfit(prices []int, fee int) int {
    cash, hold := 0, -prices[0]
    for _, price := range prices {
        cash = max(cash, hold + price - fee)
        hold = max(hold, cash - price)
    }
    return cash
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}

Explanation

Algorithm

Инициализируйте две переменные: cash, представляющую максимальную прибыль без наличия акций, и hold, представляющую максимальную прибыль с наличием акций.

Пройдите по каждому элементу массива prices и обновите значения cash и hold, используя текущую цену и комиссию.

Верните значение cash, которое будет максимальной прибылью без наличия акций.

😎