买卖股票的最佳时机 —LintCode
2017-10-12 17:08
337 查看
描述:
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
样例:
给出一个数组样例 [3,2,3,1,2], 返回 1
思路:
当我们遍历到第i天的时候,我们需要知道前i-1天的最小值。那么就可得出在第i天卖出股票的利润,每一步更新利润的最大值即可。
ac代码:
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
样例:
给出一个数组样例 [3,2,3,1,2], 返回 1
思路:
当我们遍历到第i天的时候,我们需要知道前i-1天的最小值。那么就可得出在第i天卖出股票的利润,每一步更新利润的最大值即可。
ac代码:
class Solution { public: /* * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here int minn; int maxx=0; int i,j,k,temp; if(prices.size()==0) return 0; minn=prices[0]; for(i=1;i<prices.size();i++) { temp=prices[i]-minn; if(temp<0) minn=prices[i]; maxx=max(maxx,temp); } return maxx; } };
相关文章推荐
- lintcode-150-买卖股票的最佳时机 II
- lintcode-买卖股票的最佳时机II-150
- 买卖股票的最佳时机 II-LintCode
- 【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III
- LintCode_149_买卖股票的最佳时机
- LintCode 买卖股票的最佳时机I II III IV
- LintCode:买卖股票的最佳时机 III
- lintcode:买卖股票的最佳时机 I
- Lintcode 150.买卖股票的最佳时机 II
- [Lintcode] #150 买卖股票的最佳时机 II
- Lintcode 买卖股票的最佳时机 II
- lintcode:买卖股票的最佳时机 IV
- 【LintCode】 Best Time to Buy and Sell Stock II 买卖股票的最佳时机 II
- lintcode--买卖股票的最佳时机
- 买卖股票的最佳时机 III-LintCode
- 【LintCode】 Best Time to Buy and Sell Stock 买卖股票的最佳时机
- 买卖股票的最佳时机-LintCode
- 买卖股票的最佳时机,lintcode
- **[Lintcode]Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV Leetcode
- LintCode:买卖股票的最佳时机 II