码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 121. Best Time to Buy and Sell Stock

时间:2016-06-27 21:37:06      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

Problem: https://leetcode.com/problems/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.

 

Thought:

from back to front, refresh the maximum price after prices[i] on each loop    O(n)

 

Code C++:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int profit = 0;
        if (prices.size() <= 1) {
            return profit;
        }
        
        int max_price = prices.back();
        for (int i = prices.size() - 2; i >= 0; i--) {
            if (prices[i] < max_price) {
                int diff = max_price - prices[i];
                profit = profit > diff ? profit : diff;
            }
            else {
                max_price = prices[i];
            }
        }
        return profit;
    }
};

 

LeetCode 121. Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/gavinxing/p/5621443.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!