-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d2bc9df
commit 5c904cf
Showing
1 changed file
with
29 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* 20. Valid Parentheses | ||
* You are given an array prices where prices[i] is the price of a given stock on the ith day. | ||
* You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. | ||
* Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0. | ||
* | ||
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/ | ||
*/ | ||
|
||
// O(n) time | ||
// O(n) space | ||
function maxProfit(prices: number[]): number { | ||
let highestProfit = 0; | ||
let left = 0; | ||
let right = 1; | ||
|
||
while (right < prices.length) { | ||
if (prices[left] < prices[right]) { | ||
let profit = prices[right] - prices[left]; | ||
highestProfit = Math.max(highestProfit, profit); | ||
} else { | ||
left = right; | ||
} | ||
|
||
right++; | ||
} | ||
|
||
return highestProfit; | ||
} |