-
Notifications
You must be signed in to change notification settings - Fork 0
/
buyAndSell.js
41 lines (36 loc) · 847 Bytes
/
buyAndSell.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
/**
* @param {number[]} prices
* @return {number}
*/
//o(n^2) solution
var maxProfit = function(prices) {
let maxProfit = 0;
for(i = 0; i<prices.length; i++){
for(j = i; j<prices.length; j++){
let currProfit = prices[j]-prices[i];
if(currProfit > maxProfit){
maxProfit = prices[j]-prices[i]
}
}
}
return maxProfit;
};
//O(n) solution
var maxProfit = function(prices) {
if (prices.length <= 1) {
return 0;
}
let maxProfit = 0;
let minPrice = prices[0];
for (let i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else {
const currentProfit = prices[i] - minPrice;
if (currentProfit > maxProfit) {
maxProfit = currentProfit;
}
}
}
return maxProfit;
};