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;
        }
    };
  • 相关阅读:
    多线程-工作组模式
    iOS端架构、基本组成与使用说明
    iOS,Core Animation--负责视图的复合功能
    Container Views
    IOS UIView 01-View开始深入 绘制像素到屏幕上
    View Programming Guide for iOS
    UI绘图与信息、样式
    iOS绘图框架CoreGraphics分析
    iOS开发系列--打造自己的“美图秀秀”
    Array与NSArray关系
  • 原文地址:https://www.cnblogs.com/djiankuo/p/5008697.html
Copyright © 2011-2022 走看看