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.

    If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

    class Solution 
    {
    public:
        int maxProfit(vector<int>& prices) 
        {
            if (prices.empty()) return 0;
    
            int minPrice = prices[0];
            int maxProfit = 0;
            for (int i = 1; i < prices.size(); i++)
            {
                minPrice = min(prices[i], minPrice);
                maxProfit = max(prices[i] - minPrice, maxProfit);
            }
    
            return maxProfit;
        }
    };
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int n = prices.size();
            int i,j,p=0,q=0;
            if(n == 0||n == 1)
            return p;
            int min1=prices[0],max=prices[0],max1,min=prices[0];
            int res1,res2,res3;
            for(i=1;i<n;i++)
            {
                //max=(max<prices[i])?prices[i]:max;
                //min=(min>prices[i])?prices[i]:min;
                if(max<prices[i])
                {
                    max=prices[i];
                    q=i;
                }
                if(min>prices[i])
                {
                    min=prices[i];
                    p=i;
                }
            }
    
            if(p<=q)//最小值在最大值前面
            return (max-min);
            int p1=p,q1=q+1;
            vector<int>price1;
            while(q1<p1)
            {
                price1.push_back(prices[q1]);
                q1++;
            }
    
          //  return price1[1];
            res1 =  maxProfit(price1);
            return res1;
            for(i=0;i<q;i++)//最大值在前面,找最大值前面俄最小值
            {
               min1=(min1>prices[i])?prices[i]:min1;
            }
            max1=prices[p];
             for(i=n-1;i>=p;i--)
            {
               max1=(max1<prices[i])?prices[i]:max1;
            }
    
            res2 = ((max-min1)>(max1-min))?(max-min1):(max1-min);
            res3 = (res2>res1)?res2:res1;
            return res3;
        }
    };
  • 相关阅读:
    xgboost保险赔偿预测
    XGBoost对波士顿房价进行预测
    XGBoost 重要参数(调参使用)
    xgboost与gdbt的不同和优化
    基于OpenCV制作道路车辆计数应用程序
    卷积神经网络cnn的实现
    记一次bond引起的网络故障
    虚拟化讲座
    ubuntu16安装dhcp server
    frp内网穿透新玩法--结合xshell隧道
  • 原文地址:https://www.cnblogs.com/djiankuo/p/5008697.html
Copyright © 2011-2022 走看看