Maximizing summation function with upper bound as variable. I'm trying to find the general way of optimizing a summation function and I'm a bit lost. I would like to find the maxium (and the minimum, ideally) of:
$$ \sum_{n=1}^{x} f(n)$$
For example, let's say:
$$ f(n) = -(n-4)^2 + 16 $$
In this scenario, the answer is easy to find without doing any work: f(n) is positive for $n \in [0, 8]$, and then becomes negative for infinity, we can maximize the sum by adding all positive numbers ($x = 8$).
Is there a way to find this mathematically, in a general way for all functions? Usually when looking to optimize a function I would take the derivative, but the derivative of a summation doesn't make much sense, does it?
Thanks.

Attention, please: this solution works by chance. It isn't by any means right. Sorry.

When your summation is finite, you can take its derivative, and
$$
\left(\sum_{n=0}^x f(n)\right)^\prime = \sum_{n=0}^x f^\prime(n).
$$
Assuming $f(n) = -(n-4)^2 + 16$, we obtain $f^\prime(n) = -2n + 8$ and
$$
\left(\sum_{n=0}^x f(n)\right)^\prime = \sum_{n=0}^x f^\prime(n) = 8x
- 2\sum_{n=0}^x n,
$$
which equals to $8x - x^2 - x = -x^2 + 7x$.
Solving for $x$, we find that
$$
\begin{aligned}
x(7-x) = 0 &\implies x = 0 \lor x = 7 \\
x(7-x) \ge 0 &\implies x \in [0,8). 
\end{aligned}
$$
Why did $7$ come out, instead of $8$? My guess: for $n = 8$, $f(n)$ equals zero, meaning that the $8$-th term of the summation does not provide any contribute, so the local maximum is at $n = 7$.
