File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
best-time-to-buy-and-sell-stock Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * brainstorming:
4+ * brute force
5+ *
6+ * time complexity: O(n)
7+ * space complexity: O(1)
8+ */
9+ var maxProfit = function ( prices ) {
10+ let answer , min , max ;
11+ prices . forEach ( ( price , i ) => {
12+ if ( i === 0 ) {
13+ min = price ;
14+ max = price ;
15+ answer = 0 ;
16+ return ;
17+ }
18+
19+ if ( price > max ) max = price ;
20+ if ( price < min ) {
21+ min = price ;
22+ max = price ;
23+ }
24+ answer = Math . max ( answer , max - min ) ;
25+ } ) ;
26+
27+ return answer ;
28+ } ;
Original file line number Diff line number Diff line change 1+ /**
2+ * @description
3+ * brainstorming:
4+ * brute force + hashtable
5+ *
6+ * time complexity: O(n* k log k)
7+ * space complexity: O(n* k)
8+ */
9+ var groupAnagrams = function ( strs ) {
10+ const map = new Map ( ) ;
11+ const answer = [ ] ;
12+
13+ strs . forEach ( ( str ) => {
14+ const convertedStr = str . split ( "" ) . sort ( ) . join ( ) ;
15+ if ( map . has ( convertedStr ) )
16+ map . set ( convertedStr , map . get ( convertedStr ) . concat ( str ) ) ;
17+ else map . set ( convertedStr , [ str ] ) ;
18+ } ) ;
19+
20+ map . forEach ( ( value ) => answer . push ( value ) ) ;
21+
22+ return answer ;
23+ } ;
You can’t perform that action at this time.
0 commit comments