Best Time to Buy and Sell Stock
2015-02-11 21:00
323 查看
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.
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.
class Solution { public: int maxProfit(vector<int> &prices) { int n=prices.size(); if(n==0) return 0; int tmp=prices[0]; int ans=0; for(int i=1;i<n;i++){ ans=max(prices[i]-tmp,ans); tmp=min(tmp,prices[i]); } 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
- Best Time to Buy and Sell Stock II
- [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 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