Skip to content

Commit 6c7105c

Browse files
authored
maxProfit
1 parent 81d5e7d commit 6c7105c

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function maxProfit(prices: number[]): number {
2+
3+
let minPrice: number = prices[0];
4+
let maxProfit: number = 0;
5+
6+
for (let i = 1; i < prices.length; i++) {
7+
// 1. compare the number later than now
8+
if (prices[i] < minPrice) {
9+
// 2. if there's bigger number later, set it as the standard
10+
minPrice = prices[i];
11+
} else {
12+
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
13+
}
14+
}
15+
return maxProfit;
16+
};

0 commit comments

Comments
 (0)