LeetCode:Best Time to Buy and Sell Stock

来源:互联网 发布:js正则表达式数字范围 编辑:程序博客网 时间:2024/05/16 09:22
problem:

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: 5max. 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: 0In this case, no transaction is done, i.e. max profit = 0.
这个问题实际上就是给你一串数字,让你找出这组数字中任意两个数字间最大的差值。

因为自己算法渣,当时看到这个问题的第一个想法就是,采用O(N^2)的方法,遍历两次数组,依次比较任意两个数字之间的差值,记录下最大的值。但是这种方法在LeetCode上是超时了,因为复杂度太大了。可能只遍历一边数组就可以解决这个问题。

基于这种想法,给出如下思路,我们在遍历数组的时候,我们声明两个变量,一个min1,max1,分别记录数组中最下的数字和两个数字之间的最大差值

给出代码,

class Solution {public:    int maxProfit(vector<int>& prices) {        if(prices.size()==0)        return 0;        int max1=0;        int min1=INT_MAX;        for(int i=0;i<prices.size();i++)        {            min1=min(min1,prices[i]);            max1=max(max1,prices[i]-min1);        }        return max1;    }};

0 0