[LeetCode]--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.

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^2),其中n为总天数。
       下面提供一种复杂度仅为O(n)的算法:用minimum和maxprofit分别记录当前最低价格和最大利润,采用单层循环,当前位置的价格若低于最小价格,则将其设为minimum;若高于最低价格,则profit此时为当前价格减去最小价格,若此结果比最大利润高,则将其设置为maxprofit,直到遍历到最末位置结束。
       易知,这种算法既满足了售出日期晚于购入日期,又降低了时间复杂度。

解答

class Solution {
public:
    int maxProfit(vector<int>& prices) {
    	int minimum=INT_MAX; 
        int length=prices.size();
        int maxprofit=0;
        int profit=0;
        for(int i=0;i<length;i++){
        	if(prices[i]<minimum){
        		minimum=prices[i];
			}
			else{
				profit=prices[i]-minimum;
				if(profit>maxprofit){
					maxprofit=profit;
				}
			}
		}
		return maxprofit;
    }
};






猜你喜欢

转载自blog.csdn.net/weixin_38057349/article/details/78958204