Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)_
- [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)_
Original file line number Diff line number Diff line change
@@ -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);
});
});
Original file line number Diff line number Diff line change
@@ -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;
};
Loading