zoukankan      html  css  js  c++  java
  • leetcode:Best Time to Buy and Sell Stock II

    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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).


    羞愧啊,根本不用那么复杂!直接统计每段上升序列的最大差就能够了

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if( prices.size() < 2)
                return 0;
            int max_profit = 0;
            for( int i = 1; i < prices.size(); ++i){
                if( prices[i] - prices[i-1] > 0)
                    max_profit += prices[i] - prices[i-1];
            }
            return max_profit;
        }
    };


    (之前的做法,想太多了)

    和best time to buy and sell stock的差别是同意多次买入和卖出,dp[i]保存当前能获得的最低股价

    那么max_profit就须要累加prices[i]-dp[i],这就会出现反复加的情况,比方prices 1 2 4相应dp 1 1 1,会反复加,所以每次算dp[i]要修正,取最大的prices[j]-dp[j],其余的prices[j]=dp[j]

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if( prices.size() < 2)
                return 0;
            vector< int> dp( prices.size(), INT_MAX);
            dp[0] = prices[0];
            for( int i = 1; i < prices.size(); ++i){
                int mini = prices[i];
                for( int j = i - 1; j >= 0; --j){
                    if(prices[i] - dp[j] > prices[j] - dp[j]){//保证prices[i]-dp[i]最大
                        mini = dp[j];
                        dp[j] = prices[j];
                        if( prices[j] == dp[j])
                            break;
                    }
                    else{
                        break;
                    }
                }
                dp[i] = mini;
            }
            int max_profit = 0;
            for( int i = 0; i < prices.size(); ++i){
                max_profit = prices[i] - dp[i] > 0 ? max_profit + prices[i] - dp[i] : max_profit;
            }
            return max_profit;
        }
    };


  • 相关阅读:
    Cognos11第三方权限认证之OpenDJ
    Sqlserver 2008 R2安装的盘符空间不够用的解决办法
    Cognos11中通过URL访问report的设置
    Cognos11中关于CJAP第三方认证的相关配置
    Cognos11中报XQE-JDB-0004查找驱动程序类错误
    项目管理半开源工具备份和恢复
    CentOS7.4 安装rabbitmq-3.7.x
    Spring Cloud Zuul的一个坑
    题五:10行杨辉三角
    题四:一对兔子生兔子,给个月份算有几只兔子
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4181793.html
Copyright © 2011-2022 走看看