This:
maxSubArray(A, i) = maxSubArray(A, i - 1) > 0 ? maxSubArray(A, i - 1) : 0 + A[i];
is just a pseudo code notation of the relation between maxSubArray(A, i - 1)
and maxSubArray(A, i)
. It just tells us how to compute the result for i
when we do know the result for i-1
. Read it like maths notation. Similar as
y = 5 * x
describes
int foo(int x) { return x*5; }
In the actual implementation the above recurrence relation is realized via:
dp[i] = A[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
Here dp[i - 1]
is merely accessing an element of an array. Accessing the same array element twice has no impact on complexity. Given that dp[i-1]
is not modified in that line, a compiler might optimize it to access dp[i-1]
only once.
In the presence of recursion, unnecessarily calling a function twice can have an impact on complexity. Consider this example (stolen from Jarod42):
int f(int n) {
if (n == 0) return 1;
return 2 * f(n - 1);
}
int f(int n) {
if (n == 0) return 1;
return f(n - 1) + f(n - 1);
}
Both yield the same result, but the first has linear complexity while the second is exponential.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…