Question: Part (A)
Consider the maximum subsequence sum problem (and Bentley's solution
(*)) discussed on slide 80 of the course notes
: given an integer array A, find the values i and j, which maximizes
j
∑A[k]
k=i
A solution to the problem can be solved in O(n) time as stated on slide
81. The algorithm is as follows (assuming that it is contained within a
method of an object that implements the ADT List):
public int maxSubsequenceSum() {
// pre: this is a list of integers
// post: returns the maximum sum(A[i..j]) over all indices i and j
// where 1 <= i <= j <= this.size(). If the sum is negative,
// then returns zero instead.
int nMaxSoFar = 0;
int nMaxEndingHere = 0;
for (int i = 1;
// inv:
i <= this.size(); i++) {
nMaxEndingHere = Math.max(0, nMaxEndingHere +
((Integer)(this.get(i)).intValue());
nMaxSoFar = Math.max(nMaxSoFar, nMaxEndingHere);
}
// term:
return nMaxSoFar;
}
The key to understanding this algorithm is the variable nMaxEndingHere.
Before the first assignment statement in the loop, nMaxEndingHere
contains the value of the maximum subsequence ending in position i-1;
the assignment statement modifies it to contain the value of the maximum
subsequence ending in position i. The statement increases nMaxEndingHere
by the value this[i] so long as doing so keeps it positive; when
nMaxEndingHere becomes negative, it is reset to zero (that is, the
maximum subsequence ending at i is the empty sequence).
Provide inv, an invariant for the for-loop.
Provide term, a termination condition for the for-loop.
Carefully prove that inv + exit-loop Ю term
You may assume that the code for Math.max is correct.
(*) Jon Bentley, "Programming Pearls: Algorithm Design Techniques",
Comm. ACM 27, 9 (Sept. 1984) pp. 865-871
Part (B)
Prove that the following recursive method is correct. All the assertions
you will need are given to you. You may assume that the left() and
right() methods return, respectively, the left and right subtrees of the
binary tree on which the size method is called.
Note: Since this is a recursive method, you need to use induction.
public int size () {
// pre: this is a binary tree
// post:
retu湲畮扭牥漠汥浥湥獴椠桴獩ഠ晩⠠獩浅瑰⡹
笠†⼯搠湯㩥琠楨獩攠灭祴愠摮琠楨❳楳敺椠
ര††敲畴湲〠※ഠ†素†⼯渠瑯潄敮›桴獩椠
⁴浥瑰⁹湡桴獩猧猠穩獩愠⁴敬獡⁴റ†††
畴湲ㄠ⬠氠晥⡴⸩楳敺⤨⬠爠杩瑨⤨献穩⡥㨩
Њ
”
љ
љ
Ь
&
'
I
J
Ѓ
І
љ
%
A
2І
м
т
у
&䘋
尀$摥ᬬ䴝 // sizeFound: this's size is 1 plus sum of sizes
of
// its left and right subtrees
}
