My code is working fine but it is passing only two test cases
This is because your approach is incorrect. You need to apply dynamic programming in order to solve this. Your code fails for this case.
12
50 75 52 96 89 33 20 94 95 50 71 3
Answer should be 377 but your code gives 351
https://ide.codingblocks.com/s/340680 my code is working for the test case you mentioned but still it is not passing only one test case
As I said the greedy approach is incorrect , your code fails for some testcase having n=30, you need to write dp for this.