Your logic seems perfectly correct (did not check the implementation, though) and can be implemented to give an O (n) time algorithm! Good thinking work in terms of sets.
Your right set can be implemented as a stack that supports min, and your left set can be implemented as a stack that supports max, and this gives the O (n) time algorithm.
Having a stack supporting max / min is a well-known interview question, and it can be done so that each operation (push / pop / min / max - O (1)).
To use this for your logic, the pseudocode will look something like this.
foreach elem in a[n-1 to 0] right_set.push(elem) while (right_set.has_elements()) { candidate = right_set.pop(); if (left_set.has_elements() && left_set.max() <= candidate <= right_set.min()) { break; } else if (!left.has_elements() && candidate <= right_set.min() { break; } left_set.push(candidate); } return candidate
source share