zoukankan      html  css  js  c++  java
  • Java for LeetCode 188 Best Time to Buy and Sell Stock IV【HARD】

    Say you have an array for which the ith element is the price of a given stock on day i.

    Design an algorithm to find the maximum profit. You may complete at most k transactions.

    解题思路:

    https://leetcode.com/discuss/18330/is-it-best-solution-with-o-n-o-1%E3%80%82

    本题是Best Time to Buy and Sell Stock系列最难的一道,

    参考Java for LeetCode 123 Best Time to Buy and Sell Stock III解法二的思路,四个数组可以压缩为两个数组,JAVA实现如下:

        public int maxProfit(int k, int[] prices) {
            if (k == 0 || prices.length < 2)
                return 0;
            if (k > prices.length / 2) {
                int maxProfitII = 0;
                for (int i = 1; i < prices.length; ++i)
                    if (prices[i] > prices[i - 1])
                    	maxProfitII += prices[i] - prices[i - 1];
                return maxProfitII;
            }
            int[] buy=new int[k];
            int[] sell=new int[k];
            for(int i=0;i<buy.length;i++)
            	buy[i]=Integer.MIN_VALUE;
            for (int i = 0; i < prices.length; i++)
                for (int j = k - 1; j >= 0; j--) {
                    sell[j] = Math.max(sell[j], buy[j] + prices[i]);
                    if (j == 0)
                        buy[j] = Math.max(buy[j], -prices[i]);
                    else
                        buy[j] = Math.max(buy[j], sell[j - 1] - prices[i]);
                }
            return sell[k - 1];
        }
    
  • 相关阅读:
    c/c++指针数组和数组指针
    c/c++指针传参
    c/c++指针理解
    c/c++容器操作
    c/c++ 数组传参
    c/c++ 结构体传参问题
    c++ 创建对象的三种方法
    c/c++ 随机数生成
    c++预处理指令
    团队冲刺第二阶段01
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4557321.html
Copyright © 2011-2022 走看看