【15】121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

  • Total Accepted: 161864
  • Total Submissions: 411064
  • Difficulty: Easy
  • Contributors: Admin

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.

Solution:
只需要便利一次数组,设置一个最小值当做买进值,然后把price与买进值的最大差值设为res。
res只会在数组出现递增的情况下才会大于零!
 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int res = 0;
 5         int buy = INT_MAX;//因为buy想要最小买进,所以最开始设值要最大
 6         for(int price : prices){
 7             buy = min(buy, price);
 8             res = max(res, price - buy);
 9         }
10         return res;
11     }
12 };

 















posted @ 2017-02-04 08:54  会咬人的兔子  阅读(140)  评论(0编辑  收藏  举报