[leetcode] Best Time to Buy and Sell Stock 1


Description:

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.

Tags: array, dynamic programming

自己在leetcode上AC(accept)的第一道题。

第一感觉找数组里的最大值最小值,然后相减。

后来发现它是股票,相当于时间序列,只能先买后卖。正向遍历数组,没考虑出来,越想情况越复杂。后来考虑逆向遍历,茅塞顿开。

动态规划,从最简单地情况入手,也就是最末一天入手,每次往前回溯一天。

初始条件:max为最后一天股价,profit为0.

动态规划时,考虑两种情况:

1. 如果当前天的股票价格是已知域的最高价,更新max变量;

2. 如果我在当前天买,在已知域的最高价卖,max – prices[i] > profit。则更新profit变量。

 

第一次提交没有通过,因为没有考虑输入为空的情况。

加上了判断空输入的情况,AC。

C++代码:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n = prices.size();
        int max, profit;
        if (n <= 1){
            return 0;
        }
        max = *(prices.end() - 1);
        profit = 0;
        for (int i = n - 1; i >=0; i--){
            if (prices[i] > max){
                max = prices[i];
            }
            else if(prices[i] < max - profit){
                profit = max - prices[i];
            }
        }
        return profit;
    }
};

 

代码运行效率统计

代码运行效率统计

更新:

又用Python重写了一次,这次是正向遍历,更好懂一些,本质都是动态规划:

class Solution:
    # @param prices, a list of integer
    # @return an integer
    def maxProfit(self, prices):
        if len(prices) <= 1:
            return 0
        min = prices[0]
        profit = 0
        for p in prices[1:]:
            if p < min:
                min = p
            elif p - min > profit:
                profit = p - min
        return profit

 

 


Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

One thought on “[leetcode] Best Time to Buy and Sell Stock