LeetCode - 121. Best time to buy and sell stock

 

Description

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

Input: [7, 6, 4, 3, 1]
Output: 0

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

Solution

A了题目53. maximum subarray之后,这一题思路就比较清晰了,相信各位看官稍动脑筋应该也能想到,或者看代码进行分析。

当然,特别要注意列表为空的情况(此时应返回0!)

python

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         if len(prices) == 0:
 8             return 0
 9 
10         max_diff = 0
11         cur_diff = 0
12         buy_price = prices[0]
13         for item in prices[1:]:
14             if item < buy_price:
15                 buy_price = item
16                 cur_diff = 0
17             else:
18                 cur_diff = item - buy_price
19                 max_diff = max(max_diff, cur_diff)
20 
21         return max_diff

 

cpp

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         if (prices.size()==0)
 5             return 0;
 6 
 7         int buy_price = prices.at(0);
 8         int max_diff = 0;
 9         int cur_diff = 0;
10         int temp = 0;
11         for (size_t i=1; i<prices.size(); ++i)
12         {
13             temp = prices.at(i);
14             if (temp < buy_price)
15             {
16                 buy_price = temp;
17                 cur_diff = 0;
18             }else
19             {
20                 cur_diff = temp - buy_price;
21                 max_diff = (max_diff < cur_diff ? cur_diff : max_diff);
22             }
23         }
24 
25         return max_diff;
26     }
27 };

 

 
posted @ 2017-03-28 22:05  朝研行歌  阅读(188)  评论(0编辑  收藏  举报