Leetcode NO.121 Best Time to Buy and Sell Stock
2015-03-13 09:02
337 查看
本题题目要求如下:
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.
这题我居然没有想出来。。。。太丢人了。。后来看了讨论区,恍然大悟。。
算法:
max profit只可能有两种可能性:1,这点之前的max_profit。。2,该点的值减去之前的最低点。。
这样就能轻而易取的构建出dynamic programming的模型。。。
构建dp模型的能力有待提高。。。
代码如下:
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.
这题我居然没有想出来。。。。太丢人了。。后来看了讨论区,恍然大悟。。
算法:
max profit只可能有两种可能性:1,这点之前的max_profit。。2,该点的值减去之前的最低点。。
这样就能轻而易取的构建出dynamic programming的模型。。。
构建dp模型的能力有待提高。。。
代码如下:
class Solution { public: int maxProfit(vector<int> &prices) { int sz = prices.size(); if (sz == 0) return 0; int profit = 0; int min_price = prices[0]; for (int i = 1; i < sz; ++i) { min_price = min(prices[i], min_price); profit = max(prices[i] - min_price, profit); } return profit; } };
相关文章推荐
- LeetCode--No.121--Best Time to Buy and Sell Stock
- [LeetCode] Best Time to Buy and Sell Stock
- Leetcode: Best time to buy and sell a stock I
- leetcode5: Best Time to Buy and Sell Stock
- [LeetCode] Best Time to Buy and Sell Stock II Solution
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock III
- [LeetCode] Best Time to Buy and Sell Stock 2
- [leetcode] Best Time to Buy and Sell Stock
- [LeetCode] Best Time to Buy and Sell Stock III Solution
- LeetCode Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock III
- leetcode 16: Best Time to Buy and Sell Stock III
- 【LeetCode with Python】 Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- leetcode 16: Best Time to Buy and Sell Stock III
- [leetcode]Best Time to Buy and Sell Stock III