How to solve this interview Problem?----SAP LABS Online Coding round

It came in SAP labs online coding round

I found it a bit tricky . I thought of greedy, but no pattern is coming up in my mind . Please help !!!