Skip to content

Commit 49625e5

Browse files
authored
Merge pull request #1856 from Lustellz/main
[Lustellz] WEEK05 solution
2 parents af404b7 + 8c2011e commit 49625e5

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function maxProfit(prices: number[]): number {
2+
3+
// Runtime: 1ms
4+
// Memory: 66.23MB
5+
let minPrice: number = prices[0];
6+
let maxProfit: number = 0;
7+
8+
for (let i = 1; i < prices.length; i++) {
9+
// 1. compare the number later than now
10+
if (prices[i] < minPrice) {
11+
// 2. if there's bigger number later, set it as the standard
12+
minPrice = prices[i];
13+
} else {
14+
maxProfit = Math.max(maxProfit, prices[i] - minPrice);
15+
}
16+
}
17+
return maxProfit;
18+
19+
// What I was planning to do: Recursion
20+
// Result: referring other's code
21+
};

0 commit comments

Comments
 (0)