<aside> 💡 Sort. While left is less than right: calculate sum, move left pointer for bigger sum, move right pointer for smaller sum.
</aside>
https://leetcode.com/problems/two-sum/
function twoSum(left, right, offset = []) {
while (left < right) {
const sum = // calculate sum;
if (sum === target) {
result.push( // elements... );
// 1. dedup..
// 2. move both pointers...
} else if ( // not enough ) {
// move left...
} else {
// move right
}
}
}
<aside> 💡 Right pointer always moves, compare value at right and left, when left becomes smaller move it to right.
</aside>
https://leetcode.com/problems/best-time-to-buy-and-sell-stock
function maxProfit(prices) {
let left = 0;
let right = 1;
let maxProfit = 0;
while (right < prices.length) {
// going up
if (prices[right] > prices[left]) { // update max profit }
// going down
if (prices[right] < prices[left]) { // update left }
// 💡 always moves
right++;
}
return maxProfit;
}
<aside> 💡 Iterate and store values in hashmap. If hashmap already have it, immediately return.
</aside>