[LeetCode]121. Best Time to Buy and Sell Stock(求近期股票能获得的最大利润)
2017-06-03 00:07
429 查看
121. 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.
题目大意:
有一个数组,第i个元素是第i天给定股票的价格。
如果只允许最多完成一个交易(即购买一个交易并且卖出一个股票),则设计一个算法来找到最大利润。
Example 1:
Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0.
思路1:
解决这个问题的逻辑与使用Kadane算法的“最大子阵列问题”相同。
价格数组为{1,7,4,11},利润数组则为{0 , 6 , -3 , 7}
计算原始数组的差值(maxPro+ = price [i] - price [i-1]),并找到一个连续的子阵列给出最大的利润。 如果差值低于0,请将其重置为零。
参考链接
点击查看Kadane算法的“最大子阵列问题”
代码如下:
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int>& prices) {//9ms int maxPro=0,res=0; for(int i=1; i<prices.size(); i++){ maxPro += prices[i] - prices[i-1]; maxPro = getMax(0, maxPro); res = getMax(res, maxPro); //cout << "res is = " << res << endl; } return res; } int getMax(int a, int b){return a>b ? a : b;} }; int main() { Solution s; vector<int> prices = {7, 1, 5, 3, 6, 4}; cout << "max Profit is = " << s.maxProfit(prices) << endl; return 0; }
思路2:
遍历数组,每次遍历时,找出该价格之前的最小价格,同时计算当前最小价格后的日期的能得到最大利润
minPrice是从第0天到第i天的最低价格。 maxPro是从第0天到第i天可以获得的最大利润。
在当前maxPro和prices[i] - minPrice之间获得较大的一个就是maxPro。
参考链接
代码如下:
int maxProfit(vector<int> &prices) {//9ms int maxPro = 0; int minPrice = INT_MAX; for(int i = 0; i < prices.size(); i++){ minPrice = min(minPrice, prices[i]); maxPro = max(maxPro, prices[i] - minPrice); } return maxPro; }
相关文章推荐
- LeetCode - 股票交易的最大利润
- LeetCode-714:Best Time to Buy and Sell Stock with Transaction Fee (带有抛售费用的股票最大利润) -- medium
- (LeetCode)Best Time to Buy and Sell Stock -- 求股票买卖的最大利润
- leetcode_122. Best Time to Buy and Sell Stock II 多次买卖股票,求交易的最大利润
- 假如一个数组存储了一个股票,在一天交易窗口内各时间点的股票价格(正整数),只允许一次买入和一次卖出,请提供一个算法,计算出通过买入和卖出可以得到的最大利润
- 如何买卖股票以获得最大收益 java算法
- Leetcode 121 Best Time to Buy and Sell Stock 单次买卖股票最大收益
- Leetcode 188 Best Time to Buy and Sell Stock IV 至多k次买卖股票最大收益
- leetcode——Best Time to Buy and Sell Stock III 买卖股票最大收益(AC)
- JAVA股票问题计算你能获得的最大收益
- 假如一个数组存储了一个股票,在一天交易窗口内各时间点的股票价格(正整数),只允许一次买入和一次卖出,请提供一个算法,计算出通过买入和卖出可以得到的最大利润
- 携程校招2017编程题之股票最大利润
- 投资股票以获得利润在一个小的时期
- 给你一串股票价格,找出买点和卖点,使得利润最大。
- LeetCode 121. Best Time to Buy and Sell Stock--股票买入后再卖出,求最大收益,最多交易一次
- leetcode_121. Best Time to Buy and Sell Stock 求股票的最大收益 动态规划
- 股票买卖之多次交易最大利润
- 求股票的最大利润
- Leetcode 123 Best Time to Buy and Sell Stock III 至多两次买卖股票最大收益
- [leetcode 121] Best Time to Buy and Sell Stock---只能买卖股票一次的最大收益