diff --git a/README.md b/README.md index 53ed720..ff5ef72 100644 --- a/README.md +++ b/README.md @@ -84,4 +84,6 @@ - [Task #11](src/neetcode/two-pointers/two-sum-ii-input-array-is-sorted) - _Two Sum II Input Array Is Sorted_ - _[check the task](https://neetcode.io/problems/two-integer-sum-ii)_ - [Task #12](src/neetcode/two-pointers/3sum) - _3Sum_ - _[check the task](https://neetcode.io/problems/three-integer-sum)_ - [Task #13](src/neetcode/two-pointers/container-with-most-water) - _Container With Most Water_ - _[check the task](https://neetcode.io/problems/max-water-container)_ - - [Task #14](src/neetcode/two-pointers/trapping-rain-water) - _Trapping Rain Water_ - _[check the task](https://neetcode.io/problems/trapping-rain-water)_ \ No newline at end of file + - [Task #14](src/neetcode/two-pointers/trapping-rain-water) - _Trapping Rain Water_ - _[check the task](https://neetcode.io/problems/trapping-rain-water)_ +- Sliding Window + - [Task #15](src/neetcode/sliding-window/best-time-to-buy-and-sell-stock) – _Best Time To Buy And Sell Stock_ - _[check the task](https://neetcode.io/problems/buy-and-sell-crypto)_ \ No newline at end of file diff --git a/src/neetcode/sliding-window/best-time-to-buy-and-sell-stock/solution.test.ts b/src/neetcode/sliding-window/best-time-to-buy-and-sell-stock/solution.test.ts new file mode 100644 index 0000000..4a4588b --- /dev/null +++ b/src/neetcode/sliding-window/best-time-to-buy-and-sell-stock/solution.test.ts @@ -0,0 +1,15 @@ +import { maxProfit } from './solution'; + +describe('Best Time To Buy And Sell Stock | NeetCode RoadMap | Testcases', () => { + test('#1 Buy on day 2, sell on day 5', () => { + const prices = [10, 1, 5, 6, 7, 1]; + const output = maxProfit(prices); + expect(output).toBe(6); + }); + + test('#2 No buy, no sell', () => { + const prices = [10, 8, 7, 5, 2]; + const output = maxProfit(prices); + expect(output).toBe(0); + }); +}); diff --git a/src/neetcode/sliding-window/best-time-to-buy-and-sell-stock/solution.ts b/src/neetcode/sliding-window/best-time-to-buy-and-sell-stock/solution.ts new file mode 100644 index 0000000..c5e4d54 --- /dev/null +++ b/src/neetcode/sliding-window/best-time-to-buy-and-sell-stock/solution.ts @@ -0,0 +1,21 @@ +/** + * @param {number[]} prices - an integer array, where `prices[i]` is the price of NeetCoin on the `ith` day. + * @return {number} - the maximum profit that can be achieved. + */ +export const maxProfit = (prices: number[]): number => { + let l = 0; + let r = 1; + let mxProfit = 0; + + while (r < prices.length) { + if (prices[l] < prices[r]) { + const profit = prices[r] - prices[l]; + mxProfit = Math.max(mxProfit, profit); + } else { + l = r; + } + r++; + } + + return mxProfit; +};