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;
        }
    };
  • 相关阅读:
    网络日志流量分析-第一部分.doc
    Azkaban.Sqoop_网站流量日志分析2
    飞机加油问题
    9个点画10条直线,要求每条直线上至少3个点
    vector
    Selenium VS Webdriver
    B/S测试与C/S测试之区别
    几款代码比较工具
    单元测试-圈复杂度计算
    为什么并行测试很困难以及如何使用 ConTest 辅助测试
  • 原文地址:https://www.cnblogs.com/djiankuo/p/5008697.html
Copyright © 2011-2022 走看看