File tree Expand file tree Collapse file tree 5 files changed +86
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 5 files changed +86
-0
lines changed Original file line number Diff line number Diff line change 1+ function maxProfit ( prices : number [ ] ) : number {
2+ let minPrice = Number . MAX_SAFE_INTEGER ;
3+ let maxProfit = 0 ;
4+
5+ for ( let i = 0 ; i < prices . length ; i ++ ) {
6+ if ( prices [ i ] < minPrice ) {
7+ minPrice = prices [ i ] ;
8+ }
9+
10+ const potentialProfit = prices [ i ] - minPrice ;
11+
12+ if ( maxProfit < potentialProfit ) {
13+ maxProfit = potentialProfit ;
14+ }
15+ }
16+
17+ return maxProfit ;
18+ }
Original file line number Diff line number Diff line change 1+ function containsDuplicate ( nums : number [ ] ) : boolean {
2+ return nums . length !== new Set ( nums ) . size ;
3+ }
Original file line number Diff line number Diff line change 1+ function twoSum ( nums : number [ ] , target : number ) : number [ ] {
2+ // Pair each element with its index
3+ const numsWithIndex = nums . map ( ( value , index ) => ( { value, index } ) ) ;
4+
5+ // Sort the array based on the values
6+ numsWithIndex . sort ( ( a , b ) => a . value - b . value ) ;
7+
8+ let left = 0 ;
9+ let right = numsWithIndex . length - 1 ;
10+
11+ while ( left < right ) {
12+ const sum = numsWithIndex [ left ] . value + numsWithIndex [ right ] . value ;
13+
14+ if ( sum === target ) {
15+ return [ numsWithIndex [ left ] . index , numsWithIndex [ right ] . index ] ;
16+ } else if ( sum < target ) {
17+ left ++ ;
18+ } else {
19+ right -- ;
20+ }
21+ }
22+
23+ return [ ] ; // In case there is no solution
24+ }
Original file line number Diff line number Diff line change 1+ function isAnagram ( s : string , t : string ) : boolean {
2+ if ( s . length !== t . length ) {
3+ return false ;
4+ }
5+
6+ const frequencyMap = { } ;
7+
8+ for ( const letter of s ) {
9+ if ( frequencyMap [ letter ] ) {
10+ frequencyMap [ letter ] += 1 ;
11+ } else {
12+ frequencyMap [ letter ] = 1 ;
13+ }
14+ }
15+
16+ for ( const letter of t ) {
17+ if ( frequencyMap [ letter ] ) {
18+ frequencyMap [ letter ] -= 1 ;
19+ } else {
20+ return false ;
21+ }
22+ }
23+
24+ return true ;
25+ }
Original file line number Diff line number Diff line change 1+ function isPalindrome ( s : string ) : boolean {
2+ const filteredString = s . replace ( / [ ^ a - z A - Z 0 - 9 ] / g, "" ) . toUpperCase ( ) ;
3+
4+ let [ left , right ] = [ 0 , filteredString . length - 1 ] ;
5+
6+ while ( left <= right ) {
7+ if ( filteredString [ left ] !== filteredString [ right ] ) {
8+ return false ;
9+ }
10+
11+ left += 1 ;
12+ right -= 1 ;
13+ }
14+
15+ return true ;
16+ }
You can’t perform that action at this time.
0 commit comments