-
Notifications
You must be signed in to change notification settings - Fork 9
/
121BestTimeToBuyAndSellStock.cpp
60 lines (53 loc) · 1.54 KB
/
121BestTimeToBuyAndSellStock.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <vector>
using namespace std;
class Solution
{
public:
// Using Dynamic Programming method.
// The key idea of DP is to compute the values of range from 0 to i, ie. dp[0...i], then get the result of [0...N].
int maxProfit(vector<int> &prices)
{
int min_price = INT_MAX;
int max_profit = 0;
for (int i = 0; i < prices.size(); ++i)
{
min_price = min(min_price, prices[i]);
max_profit = max(max_profit, prices[i] - min_price);
// cout << "min_price=" << min_price << ",max_profit=" << max_profit << endl;
}
return max_profit;
}
// Time Limit Exceeded
int maxProfit1(vector<int> &prices)
{
int min = prices[0];
int min_day = 0;
int max = -1;
int max_day = -1;
int profit = 0;
int max_profit = 0;
for (int i = 0; i < prices.size() - 1; ++i)
{
min = prices[i];
// cout << "min=" << min << endl;
// find max from [i, ...]
max = -1;
for (int j = i + 1; j < prices.size(); ++j)
{
if (prices[j] > max)
{
max = prices[j];
max_day = j;
// cout << "max=" << max << ",max_day=" << max_day << endl;
}
}
// find profit
profit = max - min;
if (profit > max_profit)
{
max_profit = profit;
}
}
return max_profit;
}
};