Best Time to Buy and Sell Stock

来源:互联网 发布:淘宝网q币充值软件 编辑:程序博客网 时间:2024/06/14 06:52

Best Time to Buy and Sell Stock

作者:money
标签:leetcode,C++

问题:

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.

Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

分析

按照信息论的感觉,这道题复杂度应该为O(n),但是第一次写的时候不幸写出了接近O(N2)复杂度。
使用两个指针:i,j

ai...an...amax...aj

max=amaxai

其中必然有:
ai<an<amax>aj

当出现
aj<ai
an必然比ai要大,
aiamax之间的所有数据都不用在做计算,必然不可能存在比amaxai大的数。

my solution

class Solution {public:    int maxProfit(vector<int>& prices) {        int i=0,j=1,maxi=j;        int max=0;        for(i=0;j<prices.size();)            if(prices[i]>prices[j]||j==prices.size())                {                        i=j;                        j++;                }            else                {                    if(max<prices[j]-prices[i])                            max=prices[j]-prices[i];                    j++;                }        return max;    }};
0 0
原创粉丝点击