1000. 买卖股票的最佳时机含手续费

从物理学到计算机,再到硬件,再到人工智能!
蓝桥杯备赛 (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);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_43269495/article/details/84311836
今日推荐