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

    题目: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 two transactions.

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


    思路:动态规划+从前到后

    第一种方法是:从前往后,如果比之前最小的还小,替代他,并且用ans保存当前与最小值的大小,每一次只需要判断是否比最小值小,要么就是判断与之前的最小值比较是否比ans大。

    第二种方法以后再更新。


    代码:

    //本题只能买卖1次,从前到后
    //写出了两种解法。
    class Solution1 {
    public:
    //https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
        int maxProfit(vector<int>& prices) {
            
            int ans=0;
            if(prices.empty()){
                return 0;
            }
            int low=prices[0];
            for(int i=1;i<prices.size();i++){
                if(prices[i]<low){
                    low=prices[i];
                }else if(prices[i]-low>ans){
                    ans=prices[i]-low;
                }
            }
            return ans;
        }
    };
    
     class Solution2 {
     public:
         int maxProfit(vector<int> &prices) {
             int length=prices.size();
             if(length<=1){
                 return 0;
             }
             vector<int> dp(length,0);
             int min=prices[0];
             for(int i=1;i<length;i++){
                 if(prices[i]<=min){
                     min=prices[i];
                 }
                 dp[i]=max(  dp[i-1],prices[i]-min   );
             }
             sort(dp.begin(),dp.end());
             return dp.back();
         }
     };
     
     //dp[i] 表示[0...i]内最大值,则dp[i+1]=max(dp[i],prices[i+1]-min)
     //min是[0...i]内的最小值


  • 相关阅读:
    使用Razor模板构建应用注意的细节
    分享一个秒计数器
    有效提高命中率的缓存设计
    伟大的C语言
    关于在使用Visual C++中使用MMX、SSE指令集的问题
    如何用SVN 或 WINCVS 下载x264 ffdshow T264 Kevinlib
    Visual C++图形特技
    图象处理部分文章列表
    C++,VC资源
    Visual C++ 如何:在各种字符串类型之间进行转换
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519897.html
Copyright © 2011-2022 走看看