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;
        }
    };
  • 相关阅读:
    React开发入门
    API爬虫--Twitter实战
    网页爬虫--scrapy入门
    爬虫入门(实用向)
    随谈10年的技术生涯和技术成长
    html元素的显示和隐藏
    Ubuntu下用cue文件对ape和wav文件自动分轨
    Bash内置命令exec和重定向
    Bash提示符
    Bash启动选项
  • 原文地址:https://www.cnblogs.com/djiankuo/p/5008697.html
Copyright © 2011-2022 走看看