1
+ /**
2
+ * Hackerrank
3
+ * Sunny and Johnny like to pool their money and go to the ice cream parlor.
4
+ * Johnny never buys the same flavor that Sunny does. The only other rule they
5
+ * have is that they spend all of their money.
6
+ * Given a list of prices for the flavors of ice cream, select the two that
7
+ * will cost all of the money they have.
8
+ *
9
+ * Constraints:
10
+ * 1. 2 <= m <= 10^4 (The integer m, the amount of money they have pooled)
11
+ * 2. 2 <= n <= 10^4 (The integer n, the number of flavors offered at the time)
12
+ * 3. 1 <= cost[i] <= 10^4, i ∈ [1, n]
13
+ *
14
+ * This solution got 30 points
15
+ * Problem link: http://hr.gs/eez
16
+ */
17
+
18
+ // Complete the icecreamParlor function below.
19
+ /**
20
+ *
21
+ * @param {number } m The total amount of money pooled
22
+ * @param {number[] } arr The list of ice creams with their price
23
+ */
24
+ function icecreamParlor ( m , arr ) {
25
+ const icecreamIdx = new Map ( ) ;
26
+ // Store the original indices
27
+ arr . forEach ( ( n , i ) => {
28
+ if ( icecreamIdx . has ( n ) ) {
29
+ icecreamIdx . get ( n ) . push ( i + 1 ) ;
30
+ } else {
31
+ icecreamIdx . set ( n , [ i + 1 ] ) ;
32
+ }
33
+ } ) ;
34
+ // Sort array in order to use binary search
35
+ arr . sort ( ( a , b ) => a - b ) ;
36
+ let i = 0 ;
37
+ let price = arr [ 0 ] ;
38
+ while ( i < arr . length && price < m ) {
39
+ const slicedArray = arr . slice ( i ) ;
40
+ // Use binary search to look for a value that meet the criteria
41
+ const complementIndex = binarySearch (
42
+ m - price , 0 , slicedArray . length - 1 , slicedArray
43
+ ) ;
44
+ if ( complementIndex != null ) {
45
+ // Sort and return the response
46
+ return [
47
+ icecreamIdx . get ( price ) . pop ( ) ,
48
+ icecreamIdx . get ( slicedArray [ complementIndex ] ) . pop ( )
49
+ ] . sort ( ( a , b ) => a - b ) ;
50
+ }
51
+ i ++ ;
52
+ price = arr [ i ] ;
53
+ }
54
+ return [ ] ;
55
+ }
56
+
57
+ /**
58
+ * Look for an element in array by binary search
59
+ * @param {numner } val The value to look for
60
+ * @param {number } l Left limit
61
+ * @param {number } r Right limit
62
+ * @param {number[] } arr The array where the search will be executed
63
+ */
64
+ function binarySearch ( val , l , r , arr ) {
65
+ if ( l > r ) {
66
+ return null ;
67
+ }
68
+ const mid = l + Math . floor ( ( r - l ) / 2 ) ;
69
+ if ( arr [ mid ] === val ) {
70
+ return mid ;
71
+ }
72
+ if ( arr [ mid ] > val ) {
73
+ return binarySearch ( val , l , mid - 1 , arr ) ;
74
+ } else {
75
+ return binarySearch ( val , mid + 1 , r , arr ) ;
76
+ }
77
+ }
0 commit comments