Professional Documents
Culture Documents
We have given O(n3), O(n2), O(nlogn) algorithms for the max sub-range problem. This
time, a linear time algorithm!
The idea is as follows: suppose we have found the maximum subrange sum for
x[1..n-1]. Now we have to find it for x[1..n]. There are two possibilities: either the
subrange with maximum sum still lies entirely within x[1..n-1] (in which case we
already know it), or it ends at x[n]. But if it ends at x[n], then we could determine it by
finding the suffix of x[1..n-1] with maximum sum, and then adding x[n] to that. This will
work provided it is at least 0; if it is negative we take 0 instead (which corresponds to
an empty suffix).
This suggests maintaining two different maximums: maxsofar, which is the maximum
subrange sum in the portion of the array seen so far, and maxsuffixsum, which is the
maximum suffix sum in the portion of the array seen so far. Then we simply update
both of these as we walk across: a (n) algorithm!
Maxsubrangesum5(x,n);
maxsofar := 0;
maxsuffixsum := 0;
for i := 1 to n do
maxsuffixsum := max(0, maxsuffixsum + x[i]);
maxsofar := max(maxsofar, maxsuffixsum);
return(maxsofar);
Consider this problem: given an array of n integers, the majority element is defined to
be the number that appears more than n/2 times. Can you develop an efficient
algorithm to solve the problem? (This will be in your assignment 1.)
//T(x) is As time on x
Best-case
Average-case time complexity of A
O(g(n)).
We say an algorithm runs in polynomial time if there exists a k such that its
worst-case time complexity T(n) is O(nk).
design
reduce to known problem (e.g. sorting)
recursion
divide & conquer
invent (or augment) a data structure
greedy algorithm
dynamic programming
exploit problem structure (algebraic, geometric, etc.)
probabilistic or approximate solutions
And 4 methods of analyzing algorithms
counting -- usually for worst case
(probabilistic method -- for average case)
incompressibility method -- for average case
adversary arguments -- usually for worst case lower bounds
Example 2: Given n points in the plain, find if there are three that are
colinear.
Solution 1: For each triple of points, say P1 = (x1, y1), P2 = (x2, y2), P3 =
(x3,y3), compute the slope of the line connecting P1 with P2 and P1 with P3. If
they are the same, then P1, P2, P3 are colinear. This costs O(n3).
Solution 2: For each point P, compute the slopes of all lines formed by other
points joined with P. If there is a duplicate element in this list, then there are
three colinear points. Finding a duplicate among each list costs O(n log n),
so the total cost is O(n2 log n).