-
Notifications
You must be signed in to change notification settings - Fork 0
/
best-time-to-buy-and-sell-stock.js
42 lines (33 loc) · 1.19 KB
/
best-time-to-buy-and-sell-stock.js
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
// You are given an array prices where prices[i] is the price of a given stock on the ith day.
// You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
// Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
var maxProfit = function (prices) {
let sellIdx = prices.length - 1;
let profit = 0;
for (let buyIdx = prices.length - 1; buyIdx >= 0; buyIdx--) {
let buyVal = prices[buyIdx];
let sellVal = prices[sellIdx];
if (buyVal - sellVal >= 0) {
sellIdx = buyIdx;
} else {
let price = sellVal - buyVal;
profit = Math.max(profit, price);
}
}
return profit;
};
//solution 2
var maxProfit = function (prices) {
let minPrice = Infinity;
let maxProfit = 0;
for (let i = 0; i < prices.length; i++) {
let currentPrice = prices[i];
if (currentPrice < minPrice) {
minPrice = currentPrice;
} else {
let profit = currentPrice - minPrice;
maxProfit = Math.max(maxProfit, profit);
}
}
return maxProfit;
};