zoukankan      html  css  js  c++  java
  • 买卖股票的最佳时机含手续费

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

    题目:
    给定一个整数数组 prices,其中第 i 个元素代表了第 i 天的股票价格 ;非负整数 fee 代表了交易股票的手续费用。

    你可以无限次地完成交易,但是你每笔交易都需要付手续费。如果你已经购买了一个股票,在卖出它之前你就不能再继续购买股票了。

    返回获得利润的最大值。

    注意:这里的一笔交易指买入持有并卖出股票的整个过程,每笔交易你只需要为支付一次手续费。

    示例 1:

    输入: 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.

    class Solution {
        public int maxProfit(int[] prices, int fee) {
            int len = prices.length;
            if(len == 0)
                return 0;
            
            // 数组定义:dp[i][j] 表示第i天 买入/卖出或者保持的最大利润 0代表手里没有股票 1代表持股
            int dp[][] = new int[len][2];
            
            // 初始化
            dp[0][0] = 0;
            dp[0][1] = -prices[0];  // 买入股票
            
            /**
            状态方程:dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee)
                     没有持股有两种情况,一种是前一天就没有持股,此时dp[i][0] = dp[i - 1][0]
                     另一种情况是前一天持股第i天时卖出,此时dp[i][0] = dp[i - 1][1] + prices[i] - fee
                    
                     dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i])
                     持股也有两种情况,一种是前一天已经持股那么 dp[i][1] = dp[i - 1][1]
                     另一种是前一天没有持股,第i天买入 dp[i][1] = dp[i - 1][0] - prices[i]
                     
            **/
            for(int i = 1; i < len; i++) {
                dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i] - fee);
                dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
            }
            
            return Math.max(dp[len - 1][0], dp[len - 1][1]);
        }
    }
    
  • 相关阅读:
    docker安装
    win8换win7的操作方法
    java数组实现队列
    springMVC源码学习之获取参数名
    SpringMVC源码学习之request处理流程
    LeetCode 231. Power of Two
    LeetCode 202. Happy Number
    LeetCode 171. Excel Sheet Column Number
    Eclipse 保存代码时,不自动换行设置
    LeetCode 141. Linked List Cycle
  • 原文地址:https://www.cnblogs.com/katoMegumi/p/14148493.html
Copyright © 2011-2022 走看看