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

LeetCode medium оригинал: C# #array #csharp #leetcode #math #medium

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

Пример:

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

Output: 8

C# решение

сопоставлено/оригинал
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++ решение

auto-draft, проверить перед отправкой
#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 решение

сопоставлено/оригинал
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 решение

сопоставлено/оригинал
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 решение

сопоставлено/оригинал
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 решение

сопоставлено/оригинал
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
}

Algorithm

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

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

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

😎

Вакансии для этой задачи

Показаны активные вакансии с пересечением по тегам задачи.

Все вакансии
Активных вакансий пока нет.