Skip to content

Commit f28629c

Browse files
committed
array O(n) O(1)
1 parent 4f1bffc commit f28629c

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

Diff for: leetcode-121-BestTimeToBuyAndSellStock.js

+21-9
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
11
// https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
22

3+
var maxProfit = function (prices) {
4+
let max = 0;
5+
let min = Infinity;
6+
7+
for (let p of prices) {
8+
min = Math.min(min, p);
9+
max = Math.max(max, p - min);
10+
}
11+
12+
return max;
13+
};
14+
315
// p: array
416
// num: int +
517
// e:
@@ -16,16 +28,16 @@
1628
// Output: 0
1729
// Explanation: In this case, no transactions are done and the max profit = 0.
1830

19-
var maxProfit = function (prices) {
20-
let maxProfit = 0;
21-
let min = Infinity;
22-
for (let i = 1; i < prices.length; i++) {
23-
min = Math.min(min, prices[i - 1]);
24-
maxProfit = Math.max(maxProfit, prices[i] - min);
25-
}
31+
// var maxProfit = function (prices) {
32+
// let maxProfit = 0;
33+
// let min = Infinity;
34+
// for (let i = 1; i < prices.length; i++) {
35+
// min = Math.min(min, prices[i - 1]);
36+
// maxProfit = Math.max(maxProfit, prices[i] - min);
37+
// }
2638

27-
return maxProfit;
28-
};
39+
// return maxProfit;
40+
// };
2941

3042
// var maxProfit = function(prices) {
3143
// let arr = [0];

0 commit comments

Comments
 (0)