问题
来自力扣:
假设把某股票的价格按照时间先后顺序存储在数组中,请问买卖该股票一次可能获得的最大利润是多少?
示例 1:
输入: [7,1,5,3,6,4]
输出: 5
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。
示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
限制:
0 <= 数组长度 <= 10^5
我的代码
#include <iostream>
using namespace std;
#include <algorithm>
#include <vector>
#include<queue>
#include <typeinfo>
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) return 0;
for (int i = 0; i < prices.size()-1; ++i) {
prices[i] = *(max_element(prices.begin()+i+1, prices.end())) - prices[i];
}
prices[prices.size() - 1] = 0;
return *(max_element(prices.begin(), prices.end()));
}
};
int main() {
vector<int> prices = { 7,1,5,3,6,4 };
vector<int> prices2 = { 7,6,4,3,1 };
Solution mysolution;
int s = mysolution.maxProfit(prices);
int s2 = mysolution.maxProfit(prices2);
cout << s<<"\t"<<s2;
return 0;
}
我的做法是从按先后顺序,计算在每个节点买入股票后,能获得的最大收益,然后找出那个最大值。
感觉不太高效。因为我需要遍历每个节点后面的所有节点才能确认这个节点买入的收益。(如果思路不变,然后想提高效率,可以考虑每次保存的时候保存最大的值,然后算下一个节点的时候可以不用重新遍历。不过这种做法我想了下得从最后一个节点开始算。)
示例代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() == 0){
return 0;
}
int res = 0;
for(int i = 0; i < prices.size() - 1; i++){
for(int j = i + 1; j < prices.size(); j++){
int maxprofit = prices[j] - prices[i];
if(maxprofit <= 0){
break;
}
res = max(res, maxprofit);
}
}
return res;
}
};
示例代码的做法是计算在每个节点卖出的利润。然后它记住了前面i-1个点中的最大值,所以在算第i个点时,不需要重新遍历,节省了时间消耗。