您的位置:首页 > 编程语言 > C语言/C++

[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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐