-
问题描述:假设你有一个数组,其中第 i 个元素是一支给定股票第 i 天的价格。
如果您只能完成最多一笔交易(即买入和卖出一股股票),则设计一个算法来找到最大的利润。 -
示例1:
- Input: [7,1,5,3,6,4]
- Output: 5
- Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.Not 7-1 = 6, as selling price needs to be larger than buying price.
-
示例2:
- Input: [7,6,4,3,1]
- Output: 0
- Explanation: In this case, no transaction is done, i.e. max profit = 0.
-
注意点:不要将简单问题想的复杂化。
-
代码:
#include<iostream>
using namespace std;
#include<vector>
class Solution
{
public:
int maxprofit(vector<int> src)
{
int min = INT_MAX;
int max = 0;
for (vector<int>::iterator iter = src.begin(); iter != src.end(); iter++)
{
if (*iter < min)
min = *iter;
if (max < *iter - min)
max = *iter - min;
}
return max;
}
};
int main(int argc, char* argv[])
{
vector<int> src = {7, 1, 5, 3, 6, 4};
Solution instance = Solution();
cout << "the max_profit is :" << instance.maxprofit(src) << endl;
system("pause");
}