Given a positive number S, find the largest number n such that the sum
12 + 22 + 32 + ... + n2 is less than or equal to S.
For your information, n2 = n * n
Example:
Input: S = 35 Output: 4 Explanation: 12 + 22 + 32 + 42 = 1 + 4 + 9 + 16 = 30 and 30 <= 35 if we add 52 we end up with 55, which exceeds 35 therefore 4 is the answerHints:
If we look at the explanation, a simple algorithm comes to mind:
Keep track of the
totalSoFar and start iterating from 1 as long as adding number * number to totalSoFar is less than or equal to S.You continue to add
number * number to totalSoFar as long as you don't exceed S
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check