[leetcode]Best Time to Buy and Sell Stock
2015-04-08 16:21
183 查看
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.
这一很直观,直接找差值最大就行了,一开始TLE一次,因为用了O(n^2)
的方法,后来发现O(n)就可以。
一开始的代码:
正确的:
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.
这一很直观,直接找差值最大就行了,一开始TLE一次,因为用了O(n^2)
的方法,后来发现O(n)就可以。
一开始的代码:
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size()==0 || prices.size()==1) return 0; int ans = 0 ; for(int i=1;i<prices.size();i++){ for(int j=i+1;j<prices.size();j++) if(prices[j]-prices[i] > ans) ans = prices[j]-prices[i]; } return ans; } };
正确的:
class Solution { public: int maxProfit(vector<int> &prices) { if(prices.size()==0 || prices.size()==1) return 0; int ans = INT_MIN ; int low = prices[0]; for(int i=1;i<prices.size();i++){ if(low > prices[i]) low = prices[i]; else if(prices[j] - low >ans) ans = prices[j] - low; } return ans; } };
相关文章推荐
- [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 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