stock问题

121. Best Time to Buy and Sell Stock

Difficulty: Easy

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.

Hide Company Tags Amazon Microsoft Bloomberg Uber Facebook

思路:判断每个数买和卖的问题。初始值buy是array中第一个数,从从第二个数开始判断,如果第二个数比第一个小,那就放弃第一个数,buy第二个数,因为后面的数如果比第一个大那一定比第二个大的更多。所以不断更新buy的值,同时维护benifit值。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        buy = prices[0]
        res = 0
        for i in prices[1:]:
            res = max(res, i - buy)
            buy = min(i, buy)
        return res

122. Best Time to Buy and Sell Stock II

Difficulty: Medium

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Hide Company Tags Bloomberg

思路:因为我们可以多次交易,那么只要遇到比当前价格高就卖,比当前价格低就买,累计起来就行了。比如array:[3,5,6,7],7-3=5-3+6-5+7-6,所以我们遍历了数组,每个都买一遍,遇到高的就卖掉,最后的累计就是最大盈利。

class Solution(object):
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if not prices:
            return 0
        buy = prices[0]
        res = 0
        for i in prices[1:]:
            if i > buy:
                res += i-buy
            buy = i
        return res

results matching ""

    No results matching ""