We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent e766c8c commit 24ae108Copy full SHA for 24ae108
best-time-to-buy-and-sell-stock/moonjonghoo.js
@@ -0,0 +1,24 @@
1
+/**
2
+ * @param {number[]} prices
3
+ * @return {number}
4
+ */
5
+var maxProfit = function (prices) {
6
+ let minPrices = Infinity;
7
+ let profit = 0;
8
+ for (price of prices) {
9
+ minPrices = Math.min(price, minPrices);
10
+ profit = Math.max(profit, price - minPrices);
11
+ }
12
+ return profit;
13
+};
14
+
15
16
+ let maxProfit = 0;
17
+ let currentProfit = 0;
18
+ for (let i = 1; i < prices.length; i++) {
19
+ let diff = prices[i] - prices[i - 1];
20
+ currentProfit = Math.max(0, currentProfit + diff);
21
+ maxProfit = Math.max(maxProfit, currentProfit);
22
23
+ return maxProfit;
24
0 commit comments