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

来源:互联网 发布:nat123免费域名 编辑:程序博客网 时间:2024/05/16 14:45

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

  • Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

    You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

    Return the maximum profit you can make.

    Example 1:

    Input: prices = [1, 3, 2, 8, 4, 9], fee = 2Output: 8Explanation: The maximum profit can be achieved by:Buying at prices[0] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
  • 题目大意:给定一个代表价格的数组,数组的第i个位置,代表第i天股票的价格,每次交易需要支付fee费用,可以完成多次交易,求最大收益。

  • 思路:动态规划。

  • 代码:

    package Array;import java.util.ArrayList;import java.util.List;/**- @Author OovEver- @Date 2017/11/28 10:10*/  public class Solution {  public int maxProfit(int[] prices, int fee) {    if (prices == null || prices.length == 0) {        return 0;    }      //        手里没有股票       int cash = 0;      //        手里持有股票       int hold = -prices[0];    for(int i=1;i<prices.length;i++) {        cash = Math.max(cash, hold + prices[i] - fee);        hold = Math.max(hold, cash - prices[i]);    }    return Math.max(cash, hold);}}
阅读全文
0 0
原创粉丝点击