• 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]内的最小值


  • 相关阅读:
    Eclipse自动换行插件
    JAVA中super与this的区别
    外网访问PG数据库,如何赋予IP访问权限
    PostgreSQL环境变量与psql命令的替代作用
    \l 的使用
    一次生成任意多行数据的语句
    equals与==的区别
    PostgreSQL 名词理解EXPLAIN VERBOSE
    PG坑爹的数组定义
    【收藏】常用的ftp命令
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519897.html
Copyright © 2020-2023  润新知