-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path121_BestTimetoBuyandSellStock.cpp
37 lines (31 loc) · 1.07 KB
/
121_BestTimetoBuyandSellStock.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "stdafx.h"
//-------------------------------------------------------------------------
#include <limits>
#include <algorithm>
class Solution {
public:
int maxProfit(vector<int> const& prices) {
int result = 0;
int minPrice = std::numeric_limits<int>::max();
for (auto price : prices) {
if (price > minPrice) {
result = max(result, price - minPrice);
} else {
minPrice = price;
}
}
return result;
}
};
//-------------------------------------------------------------------------
int main() {
Solution so;
cout << so.maxProfit(vector<int>{}) << endl;
cout << so.maxProfit(vector<int>{ 1 }) << endl;
cout << so.maxProfit(vector<int>{ 1, 2 }) << endl;
cout << so.maxProfit(vector<int>{ 2, 1 }) << endl;
cout << so.maxProfit(vector<int>{ 1, 2, 3, 4 }) << endl;
cout << so.maxProfit(vector<int>{ 1, 4, 3, 2 }) << endl;
cout << so.maxProfit(vector<int>{ 4, 3, 2, 1 }) << endl;
cout << so.maxProfit(vector<int>{ 4, 1, 2, 3 }) << endl;
}