-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path121.cpp
More file actions
47 lines (43 loc) · 1.11 KB
/
121.cpp
File metadata and controls
47 lines (43 loc) · 1.11 KB
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
//
// 121.cpp
// LeetCode
//
// Created by 张佐玮 on 15/7/20.
// Copyright (c) 2015年 JarvisZhang. All rights reserved.
//
// Title: Best Time to Buy and Sell Stock
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfitDP(vector<int>& prices) {
if (prices.empty()) {
return 0;
}
int current = 0, profit = 0;
for (int i = 1; i < prices.size(); i++) {
current = max(current - prices[i-1] + prices[i], 0);
profit = max(current, profit);
}
return profit;
}
int maxProfit(vector<int>& prices) {
if (prices.empty()) {
return 0;
}
int maximum = prices[0], minimum = prices[0], profit = 0;
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > maximum) {
maximum = prices[i];
profit = max(profit, maximum - minimum);
}
if (prices[i] < minimum) {
minimum = prices[i];
maximum = minimum;
}
}
return profit;
}
};