-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParenthesesPerfectionKit.java
More file actions
236 lines (184 loc) · 8.43 KB
/
ParenthesesPerfectionKit.java
File metadata and controls
236 lines (184 loc) · 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package Algorithms.Strings;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Stack;
import java.util.TreeSet;
/**
<pre>
At Amazon, a user owns a unique tool called the
"Parentheses Perfection Kit." This kit contains different types of parentheses, each with a specific efficiency rating. The goal is to create a balanced sequence of parentheses by adding zero or more parentheses from the kit to maximize the sequences total EfficiencyScore. The EfficiencyScore of a sequence is the sum of the efficiency ratings of the parentheses used from the kit.
A sequence is considered balanced if it has an equal number of opening '(' and closing )' parentheses, with each opening parentheses properly matched with a closing one in the correct order (i.e., circular balance). For instance, sequences like (()), (), and (()()) are balanced, while sequences like ), ((), and (()(())) are not.
You are given an initial parentheses sequence represented by the string s, along with a Parentheses Perfection Kit containing different types of parentheses in the form of the string kitParentheses and their respective efficiency ratings in the efficiencyRatings array (both of size m). The EfficiencyScore of the original strings is initially 0. You can use any number of unused parentheses from the kit to create the final sequence, as long as the final sequence remains balanced.
The task is to determine the maximum possible EfficiencyScore that can be achieved for the resulting balanced sequence
Note: It is guaranteed that the sequence can be made balanced by adding zero or more parentheses from the kit.
Sample Case 0
Sample Input 0
STDIN Function
() → s = "() "
(()) → kitParentheses = "(())"
4 → efficiencyRatings[] size m=4
4 → efficiencyRatings = [4, 2, -3, -3]
2
-3
-3
# Example 1
s = "()"
kit = "(())"
efficiency_rating = [4, 2, -3, -3]
print(find_max_to_balance(s, kit, efficiency_rating)) # Output: 1
# Example 2
s = ")(("
kit = ")(()))"
efficiency_rating = [3,4,2,-4,-1,-3]
print(find_max_to_balance(s, kit, efficiency_rating)) # Output: 6
Explanation
If the user used the 0th indexed and 2nd indexed parentheses from the bag and add them to the start and end of the
string respectively, then the final balanced sequence will be "(0)" with a total EfficiencyScore of 4 + (-3) = 1. There are
no other combinations of adding parentheses that can yield a balanced sequence with total EfficiencyScore greater than 1, Hence return 1 as answer.
consider ")(", ")((", ")(()))" scenarios
</pre>
* @author Srinivas Vadige, srinivas.vadige@gmail.com
* @since 11 Jan 2025
* @see {@link Algorithms.DynamicProgramming.LongestValidParenthesis}
*/
public class ParenthesesPerfectionKit {
public static void main(String[] args) {
String s = "())()()";
String kit = "()()()";
int[] efficiencyRating = { 5,5,5,5,5,5 };
// String s = "))(()";
// String kit = "(())";
// int[] efficiencyRating = { 4, 2, -3, -1 };
System.out.println("findMaxToBalance using PriorityQueue My Approach : " + findMaxToBalanceUsingPriorityQueueMyApproach(s, kit, efficiencyRating));
// System.out.println("findMaxToBalance using PriorityQueue : " + findMaxToBalanceUsingPriorityQueue(s, kit, efficiencyRating));
// System.out.println("findMaxToBalance using TreeSet : " + findMaxToBalanceUsingTreeSet(s, kit, efficiencyRating));
}
/**
s = ")(("
kit = ")(()))"
efficiency_rating = [3,4,2,-4,-1,-3]
print(find_max_to_balance(s, kit, efficiency_rating)) # Output: 6
the map of kit and efficiency_rating looks like:
) ( ( ) ) )
3 4 2 -4 -1 -3
which is same as
( (
4 2
*
) ) ) )
3 -1 -3 -4
* *
"(" openOrphanCount == ")" close efficiency counter-part and vice-versa
s = ")(("
Here, we have 2 openOrphans and 1 closeOrphans then we need to add 2 maxCloseEfficiencies and 2 maxOpenEfficiency
i.e
2 openOrphans + 1 closeOrphans=> 2 ")" closeEff + 1 "(" openEff => 3+(-1)+4 => 6
*/
// TODO: validate open & close count with different test cases
public static int findMaxToBalanceUsingPriorityQueueMyApproach(String s, String kit, int[] efficiencyRating) {
int open, close; open=close=0; // '(' open orphan count and ')' close orphan count
// check if s is balanced or not AND // get orphanOpenCount & orphanCloseCount
for (String s1 : s.split("")){
if (s1.equals("(")) {
open++;
}
else if (s1.equals(")")) {
if (open == 0) close++;
else open--; // decrease '(' open orphan count when it becomes balanced
}
}
if (open == 0 && close == 0) return 1;
// Prepare PQs
PriorityQueue<Integer> openPQ = new PriorityQueue<>(Comparator.reverseOrder());
PriorityQueue<Integer> closePQ = new PriorityQueue<>(Comparator.reverseOrder());
for (int i = 0; i < kit.length(); i++) {
if(kit.charAt(i)=='(')
openPQ.add(efficiencyRating[i]);
else closePQ.add(efficiencyRating[i]);
}
// sum all the orphans efficiency score
// "(" openOrphanCount = ")" close counter part and vice-versa
int max = 0;
for (;open>0;open--)
max += closePQ.isEmpty()?0:closePQ.poll();
while(close>0) {
max += openPQ.isEmpty()?0:openPQ.poll();
close--;
}
return max;
}
public static int findMaxToBalanceUsingPriorityQueue(String s, String kit, int[] efficiencyRating) {
Stack<Character> tmpStack = new Stack<>();
PriorityQueue<Integer> openPQ = new PriorityQueue<>(Comparator.reverseOrder());
PriorityQueue<Integer> closePQ = new PriorityQueue<>(Comparator.comparingInt(a -> -a));
for (int i = 0; i < kit.length(); i++) {
if (kit.charAt(i) == '(')
openPQ.add(efficiencyRating[i]);
else
closePQ.add(efficiencyRating[i]);
}
int max = 0;
// Loop over String to find all needed to balance the string
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ')' && tmpStack.isEmpty())
if (!openPQ.isEmpty()) max += openPQ.poll(); // We need opening parenthesis
else if (s.charAt(i) == ')' && tmpStack.peek() == '(')
tmpStack.pop();
else tmpStack.push(s.charAt(i));
}
while (!tmpStack.isEmpty()) {
if (tmpStack.pop() == '(')
if (!closePQ.isEmpty()) max += closePQ.poll();
else
if (!openPQ.isEmpty()) max += openPQ.poll();
}
while (!openPQ.isEmpty() && !closePQ.isEmpty())
max = Math.max(max, openPQ.poll() + closePQ.poll() + max);
return max;
}
/*
TreeSet can't handle duplicates
*/
@SuppressWarnings("unused")
public static int findMaxToBalanceUsingTreeSet(String s, String kit, int[] efficiencyRating) {
int open, close; open=close=0;
// check if s is balanced or not
for (String s1 : s.split("")){
if (s1.equals("(")) {
open++;
}
else if (s1.equals(")")) {
if (open == 0)
close++;
else
open--; // sub parenthesis balanced
}
}
if (open == close) return 1;
int max = 0;
String needed = (open>close)? "(" : ")";
// Prepare TreeSet
Map<String, TreeSet<Integer>> map = new HashMap<>(); // or we can use "new PriorityQueue<>(Comparator.reverseOrder());"
for (int i = 0; i < kit.length(); i++) {
String key = kit.charAt(i)+"";
if(map.containsKey(key)){
map.get(key).add(efficiencyRating[i]);
} else {
TreeSet<Integer> set = new TreeSet<>(Comparator.reverseOrder());
set.add(efficiencyRating[i]);
map.put(key, set);
}
}
while(open>0) {
max += (map.containsKey("(")&&!map.get("(").isEmpty()) ? map.get("(").pollFirst():0;
open--;
}
while(close>0) {
max += (map.containsKey(")")&&!map.get(")").isEmpty()) ? map.get(")").pollFirst():0;
close--;
}
return max;
}
}