Hi everyone,
I have coded the following solution for the aforementioned problem, yet only 4 of the total 14 test cases pass upon submission. It works for all the test cases given in the problem description.
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N, v;
scanf("%d", &N);
int maxDepth = 0, depth = 0; // alternating depth variables
int prevOpen = 0, prevClose = 0; // previous opening or closing character
int pDepth = 0, bDepth = 0; // depth of parenthesis () and depth of square brackets []
int maxPWidth = 0, pPos = 0; // variables for calculating maximum width
int maxBWidth = 0, bPos = 0;
for (int i = 0; i < N; ++i) {
scanf("%d", &v);
switch (v) {
case 1: case 3:
// ( or [ with their respective depths as 0
// then save that starting pos
if (v == 1) {
if (!pDepth)
pPos = i;
++pDepth;
} else {
if (!bDepth)
bPos = i;
++bDepth;
}
// calculate max alternating depth
if (v != prevOpen)
maxDepth = max(++depth, maxDepth), prevOpen = v;
break;
case 2: case 4:
// ) or ] is encountered and their respective depths are 0
// compare that width with their respective max widths
if (v == 2) {
--pDepth;
if (!pDepth)
maxPWidth = max(i-pPos+1, maxPWidth);
} else {
--bDepth;
if (!bDepth)
maxBWidth = max(i-bPos+1, maxBWidth);
}
// alternate depth calculation
if (v != prevClose)
--depth, prevClose = v;
if (!depth) // reset these variables for the next set of brackets starting at depth 0
prevOpen = prevClose = 0;
break;
}
}
printf("%d %d %d", maxDepth, maxPWidth, maxBWidth);
return 0;
}
I can’t think of any corner cases for this specific problem, actually stuck.
Help/Suggestions on the above code would be really appreciated.
Regards,
Vikrant.