從物理學到計算機,再到硬件,再到人工智能!
藍橋杯備賽 (LintCode上刷的第十四題)
問題描述
現在給出一個數組,包含一系列價格,其中第i個元素是一支股票在第i天的價格;一個非負數fee代表了手續費。
你可以根據需要任意地進行交易,但是每次交易都必須付手續費。每次購買不能超過1股(必須在再次購買的之前賣出股票)。
返回可以獲得的最大利潤。
注意:0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.
樣例輸出
輸入: prices = [1, 3, 2, 8, 4, 9], fee = 2
輸出: 8
解釋: 最大利潤的獲得方式爲:
買入 prices[0] = 1
賣出 prices[3] = 8
買入 prices[4] = 4
賣出 prices[5] = 9
總利潤爲 ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
問題分析
JAVA代碼實現
package DP;
public class MaxProfit1000_1120 {
/**
* 買賣股票的最大利潤:只要有利潤就可拋售即價格差-手續費>0即可
* @param prices 價格數組
* @param fee 手續費
* @return
*/
public static int maxProfit(int[] prices, int fee) {
//min記錄價格數組中價格最小的值
int min = prices[0];
//記錄利潤
int profit = 0;
//遍歷價格數組的每一個元素
for (int i = 1; i < prices.length; i++) {
//當前價格更小則更新價格最小值
if (prices[i] < min) {
min = prices[i];
}
//如果滿足拋售條件:價格差-手續費>0
if (prices[i] - min > fee) {
//利潤累加
profit = prices[i] - min - fee + profit;
//更新價格最小值
min = prices[i];
}
}
return profit;
}
public static void main(String[] args) {
int[] prices = {3, 2, 2, 8, 4, 9};
int fee = 2;
int profit = maxProfit(prices, fee);
System.out.println(profit);
}
}