题目:
假设把某股票的价格按照时间存储在数组中,请问买卖股票一次可获得的最大利润是多少?例如,一支股票在某些时间的价格{9,11,8,5,7,12,16,14}.如果我们能在价格为5的时候买入,16的时候卖出,那么将获得最大利润11。
解题思路:
1.使用暴力匹配时间复杂度为O(n2)
2.在利润固定时,找出前面最小的数,往后遍历在找最大的数,找出最大利润
参考答案:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <stack>
#include <queue>
#include <list>
#include <unordered_map>
#include <cstring>
#include <map>
using namespace std;
class Solution {
public:
int max_profit_Solution(vector<int> array)
{
if (array.empty() || (array.size()<2))
return 0;
int profit = array[1] - array[0];
int pre_val = array[0];
for (int j = 2; j < array.size(); ++j) {
if (profit < (array[j]-pre_val))
profit = (array[j]-pre_val);
if (pre_val > array[j])
pre_val = array[j];
}
return profit;
}
};
int main()
{
vector<int> my_res;
vector<int> res;
Solution solution;
my_res.push_back(9);
my_res.push_back(11);
my_res.push_back(8);
my_res.push_back(5);
my_res.push_back(7);
my_res.push_back(12);
my_res.push_back(16);
my_res.push_back(14);
cout<<solution.max_profit_Solution(my_res)<<endl;
return 0;
}