Those sites are giving you challenges.
Quote:is it not optimized.
Optimizing is exactly the object of the challenge. Most strait forward solution is never the right solution.
Your program is optimum if requested 1 sum, but not if you are requested many partial sums.
Said otherwise, the solution is a trade off, you spend time to compute something that will help you to get fast answers.
Your challenge is to find how to do, if we give you the solution, then you fail the challenge.