File tree Expand file tree Collapse file tree 5 files changed +73
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 5 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 1+ var maxProfit = function ( prices ) {
2+ let lowBuy = prices [ 0 ] ;
3+ let profit = 0 ;
4+ // loop over the array
5+ for ( let i = 0 ; i < prices . length ; i ++ ) {
6+ // to set lowBuy to adjust as lower numbers
7+ if ( prices [ i ] < lowBuy ) {
8+ lowBuy = prices [ i ] ;
9+ }
10+ // check the subtract current iteration on array - lowBuy price to calculate current profit
11+ if ( prices [ i ] - lowBuy > profit ) {
12+ profit = prices [ i ] - lowBuy ;
13+ }
14+ }
15+ return profit ;
16+ } ;
Original file line number Diff line number Diff line change 1+ var containsDuplicate = function ( nums ) {
2+ let set = new Set ( [ nums [ 0 ] ] ) ;
3+
4+ // check if the current value is in the set
5+ for ( let i = 1 ; i < nums . length ; i ++ ) {
6+ // if it's already in the set, return true
7+ if ( set . has ( nums [ i ] ) ) {
8+ return true ;
9+ // if it's not in the set, add it to set and resume
10+ } else {
11+ set . add ( nums [ i ] ) ;
12+ }
13+ }
14+ return false ;
15+ } ;
Original file line number Diff line number Diff line change 1+ var twoSum = function ( nums , target ) {
2+ const hash = new Map ( ) ;
3+
4+ for ( let i = 0 ; i < nums . length ; i ++ ) {
5+ // find num to make a target
6+ const findTarget = target - nums [ i ] ;
7+
8+ // if find num, return
9+ if ( hash . get ( findTarget ) !== undefined ) return [ hash . get ( findTarget ) , i ] ;
10+
11+ // if couldn't find, set in the map
12+ hash . set ( nums [ i ] , i ) ;
13+ }
14+
15+ return [ ] ;
16+ } ;
Original file line number Diff line number Diff line change 1+ var isAnagram = function ( s , t ) {
2+ firstList = s . split ( "" ) . sort ( ) ;
3+ secondList = t . split ( "" ) . sort ( ) ;
4+
5+ // compare if these are same and return
6+ return JSON . stringify ( firstList ) === JSON . stringify ( secondList ) ;
7+ } ;
Original file line number Diff line number Diff line change 1+ var isPalindrome = function ( s ) {
2+ let regex = / [ ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \] ^ _ ` { | } ~ " " ] / g;
3+ let convertToLowerCase = s . replace ( regex , '' ) . toLowerCase ( ) ;
4+ let middleOftheString = parseInt ( convertToLowerCase . length / 2 ) ;
5+ let result ;
6+
7+ // iterate over each value of string till to reache the middle of the string
8+ for ( let i = 0 ; i <= middleOftheString ; i ++ ) {
9+ // check if values match
10+ if ( convertToLowerCase [ i ] === convertToLowerCase [ convertToLowerCase . length - 1 - i ] ) {
11+ result = true ;
12+ // if there's nothing else to check for, return false and break the loop
13+ } else {
14+ result = false ;
15+ break ;
16+ }
17+ }
18+ return result ;
19+ } ;
You can’t perform that action at this time.
0 commit comments