Skip to content

Commit 5972c4a

Browse files
committed
Added best time solution
1 parent 7e447b5 commit 5972c4a

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} prices
3+
* @return {number}
4+
*/
5+
var maxProfit = function (prices) {
6+
// Initiate left and right pointer (left: buy price / right: sell price)
7+
// Make profit with initiative value 0
8+
let l = 0;
9+
let r = 1;
10+
let profit = 0;
11+
// Iterate to check profit = prices[r] - prices[l]
12+
while (r < prices.length) {
13+
// If profit is positive, compare profit with previous one
14+
if (prices[r] > prices[l]) {
15+
profit = Math.max(profit, prices[r] - prices[l]);
16+
r++;
17+
} else {
18+
// If profit is negative, move forware left and right pointer
19+
l = r;
20+
r++;
21+
}
22+
}
23+
return profit;
24+
};
25+
26+
// TC: O(n)
27+
// SC: O(3)
28+
29+
console.log(maxProfit([7, 1, 5, 3, 6, 4])); //5
30+
console.log(maxProfit([7, 6, 4, 3, 1])); //0

valid-anagram/nhistory.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,10 @@ var isAnagram = function (s, t) {
1818
if (s.length !== t.length) return false;
1919
// Put a character and add or substract number
2020
for (let i = 0; i < s.length; i++) {
21-
map[s[i]] = map[s[i]] ? map[s[i]] + 1 : 1;
22-
map[t[i]] = map[t[i]] ? map[t[i]] - 1 : -1;
21+
// map[s[i]] = map[s[i]] ? map[s[i]] + 1 : 1;
22+
map[s[i]] = (map[s[i]] ?? 0) + 1;
23+
// map[t[i]] = map[t[i]] ? map[t[i]] - 1 : -1;
24+
map[t[i]] = (map[t[i]] ?? 0) - 1;
2325
}
2426

2527
for (let i = 0; i < s.length; i++) {

0 commit comments

Comments
 (0)