zoukankan      html  css  js  c++  java
  • LeetCode——Best Time to Buy and Sell Stock IV

    Description:

    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.

    Note:
    You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    动态规划,有递推式:参考:http://blog.csdn.net/feliciafay/article/details/45128771

    local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),

    global[i][j]=max(local[i][j],global[i-1][j])

    public class Solution {
        public int maxProfit(int k, int[] prices) {
            
            int len = prices.length;
            
            if(len < 2) {
                return 0;
            }
            
            if(k > len) {
                return bigProfit(prices);
            }
            
            int[] local = new int[k+1];
            int[] global = new int[k+1];
            
            Arrays.fill(local, 0);
            Arrays.fill(global, 0);
            
            for(int i=0; i<len-1; i++) {
                int diff = prices[i+1] - prices[i];
                for(int j=k; j>=1; j--) {
                    local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);
                    global[j] = Math.max(global[j], local[j]);
                }
            }
            
            return global[k];
        }
        
        
        public int bigProfit(int[] prices) {
            
            int res = 0;
            for(int i=0; i<prices.length-1; i++) {
                if(prices[i] < prices[i+1]) {
                    res += prices[i+1] - prices[i];
                }
            }
            
            return res;
            
        }
        
    }
  • 相关阅读:
    GridView 内部添加控件
    TreeList获取选中内容
    TreeList简介
    TreeList
    DEV—【GridControl 按钮列无法触发点击事件解决方案】
    dev 多行文本 MemoEdit
    DevExpress控件使用小结
    DEV常用设置
    DEV常用设置
    documentManager1注意事项
  • 原文地址:https://www.cnblogs.com/wxisme/p/4861702.html
Copyright © 2011-2022 走看看