714. Best Time to Buy and Sell Stock with Transaction Fee
Вам дан 配列 prices, где prices[i] - это цена данной акции в i-й день, и 整数 fee, представляющее собой комиссию за сделку. find максимальную прибыль, которую вы можете получить. Вы можете совершить сколько угодно сделок, но за каждую сделку вам придется заплатить комиссию. Примечание: Вы не можете совершать несколько сделок одновременно (то есть вы должны продать акции, прежде чем купить их снова). Комиссия за сделку взимается только один раз за каждую покупку и продажу акций.
例:
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++ 解法
自動ドラフト、提出前に確認#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, представляющую максимальную прибыль с наличием акций.
Пройдите по каждому elementу 配列а prices и обновите значения cash и hold, используя текущую цену и комиссию.
return значение cash, которое будет максимальной прибылью без наличия акций.
😎
Vacancies for this task
有効な求人 with overlapping task tags are 表示.