File tree Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Expand file tree Collapse file tree 2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number } n
3
+ * @return {number }
4
+ */
5
+ const integerBreak = function ( n ) {
6
+ if ( n <= 2 ) return 1 ;
7
+
8
+ const maxArr = [ ] ;
9
+ for ( let i = 0 ; i < n + 1 ; i ++ ) {
10
+ maxArr [ i ] = 0 ;
11
+ }
12
+
13
+ /** For a number i: write i as a sum of integers, then take the product of those integers.
14
+ maxArr[i] = maximum of all the possible products */
15
+
16
+ maxArr [ 1 ] = 0 ;
17
+ maxArr [ 2 ] = 1 ; // 2=1+1 so maxArr[2] = 1*1
18
+
19
+ for ( let i = 3 ; i <= n ; i ++ ) {
20
+ for ( let j = 1 ; j < i ; j ++ ) {
21
+ /** Try to write i as: i = j + S where S=i-j corresponds to either one number or a sum of two or more numbers
22
+
23
+ Assuming that j+S corresponds to the optimal solution for maxArr[i], we have two cases:
24
+ (1) i is the sum of two numbers, i.e. S=i-j is one number, and so maxArr[i]=j*(i-j)
25
+ (2) i is the sum of at least three numbers, i.e. S=i-j is a sum of at least 2 numbers,
26
+ and so the product of the numbers in this sum for S is maxArr[i-j]
27
+ (=maximum product after breaking up i-j into a sum of at least two integers):
28
+ maxArr[i] = j*maxArr[i-j]
29
+ */
30
+ maxArr [ i ] = Math . max ( maxArr [ i ] , j * ( i - j ) , j * maxArr [ i - j ] ) ;
31
+ }
32
+ }
33
+ return maxArr [ n ] ;
34
+ } ;
Original file line number Diff line number Diff line change
1
+ /**
2
+ * @param {number[][] } wall
3
+ * @return {number }
4
+ */
5
+ const leastBricks = function ( wall ) {
6
+ const hash = { } ;
7
+ let row ;
8
+ let rowSum = 0 ;
9
+ for ( let i = 0 ; i < wall . length ; i ++ ) {
10
+ rowSum = 0 ;
11
+ row = wall [ i ] ;
12
+ for ( let j = 0 ; j < row . length - 1 ; j ++ ) {
13
+ rowSum += row [ j ] ;
14
+ hash [ rowSum ] = hash . hasOwnProperty ( rowSum ) ? hash [ rowSum ] + 1 : 1 ;
15
+ }
16
+ }
17
+ return (
18
+ wall . length -
19
+ ( Object . keys ( hash ) . length > 0
20
+ ? Math . max ( ...Object . keys ( hash ) . map ( key => hash [ key ] ) )
21
+ : 0 )
22
+ ) ;
23
+ } ;
24
+
25
+ console . log ( leastBricks ( [ [ 1 ] , [ 1 ] , [ 1 ] ] ) ) ;
You can’t perform that action at this time.
0 commit comments