Skip to content

Commit

Permalink
feat(array): Buy sell stocks
Browse files Browse the repository at this point in the history
  • Loading branch information
xlreon committed Oct 27, 2023
1 parent c936097 commit 9622b9a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@

### 1. Two Sum

> Use HashMap to determine indexes
> Use HashMap to determine indexes - O(n)
### 2. Buy Sell Stocks

> Keep finding minimum and updating maxProfit for each iteration - O(n)
15 changes: 15 additions & 0 deletions array/buy-sell-stocks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let min = Number.MAX_SAFE_INTEGER
let maxProfit = 0;
for(let i = 0; i < prices.length; i++) {
const curr = prices[i];
const profit = curr - min;
min = Math.min(curr, min)
maxProfit = Math.max(profit, maxProfit)
}
return maxProfit;
};

0 comments on commit 9622b9a

Please sign in to comment.