前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >​LeetCode刷题实战188:买卖股票的最佳时机 IV

​LeetCode刷题实战188:买卖股票的最佳时机 IV

作者头像
程序员小猿
发布2021-03-04 14:20:57
2120
发布2021-03-04 14:20:57
举报
文章被收录于专栏:程序IT圈程序IT圈

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 买卖股票的最佳时机 IV,我们先来看题面:

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv

You are given an integer array prices where prices[i] is the price of a given stock on the ith day. Design an algorithm to find the maximum profit. You may complete at most k transactions. Notice that you may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

题意

给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。

设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。

注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。

示例

代码语言:javascript
复制
示例 1:

输入:k = 2, prices = [2,4,1]
输出:2
解释:在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。

示例 2:

输入:k = 2, prices = [3,2,6,5,0,3]
输出:7
解释:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
 

提示:

0 <= k <= 100
0 <= prices.length <= 1000
0 <= prices[i] <= 1000

解题

思路:无非四种状态 当天买入不买或者卖出不卖 ,我们得到状态转移方程

buy[i]=max(buy[i],sell[i-1]-prices) //buy[i]代表第i笔买入自己还剩的钱 买入则减去当天的价格

sell[i]=max(sell[i],buy[i]+prices[i]) //selle[i]代表第i笔卖出后自己还剩的钱 卖出即加入当天的价格

代码语言:javascript
复制
class Solution { 
    public int quick(int[] prices){
        int max=0;
        for(int i=0;i<prices.length-1;i++){
            if(prices[i+1]>prices[i])
            max+=(prices[i+1]-prices[i]);
        }
        return max;
    }
    
    public int maxProfit(int k, int[] prices) {
        int len=prices.length;
       
      if(len==1||len==0||prices==null||k==0){
          return 0;
      }
      if(k>=len/2){
        return quick(prices);
      } 
        int []buy=new int[k+1];
        int []sell=new int[k+1];
        for(int i=0;i<=k;i++){
            buy[i]=Integer.MIN_VALUE;
        }
        for(int i=0;i<len;i++){ 
            for (int j = 0; j<k; j++) {
                buy[j+1] = Math.max(buy[j+1], sell[j] - prices[i]);
                sell[j+1] = Math.max(buy[j+1] + prices[i], sell[j+1]);
            }
            
        }
        return sell[k];
        
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-02-19,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员小猿 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题意
  • 示例
  • 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档