Need idea: Tried to solve it using bitmask + segment tree, but getting WA. Any idea about how to solve this problem efficiently?