Problem Description: Suppose you are given the price of a stock on each day, and you have to decide when to buy and when to sell to maximize the profit. Note that you cannot sell before you buy.
Naive strategy: Try all pairs of (buy, sell) dates, where the buy date must be before the sell date. This takes \Theta(n^2) time.
Naive strategy
Divide and conquer strategy: Instead of daily price, consider the daily change in price, which can be either positive or negative number. Let array A store these changes. Now we have to find the subarray of A that maximizes the sum of the numbers in that subarray.
Algorithm: - Divide the array into two. - Find the max subarray in the first half and second half separately. - Find the max subarray crossing the two halves. - Return the max of three.
Max subarray algorithm
Suppose T(n) be the time complexity of the algorithm FIND-MAXIMUM-SUBARRAY. Then we can write the recurrence as follows: [ T(n) = 2T(n/2) + (n) ]
Given n points and arbitrary distances between them, find the closest pair. (E.g., think of distance as airfare - This is not Euclidean distance!)
Closest pair example
Must look at all pairwise distances, else any one you didn’t check might be the shortest.
Is this true for Euclidean distance in 1-2 dimensions?
Given n points on the real line, find the closest pair.
1D Closest Pair
Key point: do not need to calculate distances between all pairs: exploit geometry + ordering.
Closest pair. Given n points in the plane, find a pair with smallest Euclidean distance between them.
Brute force. Check all pairs of points p and q with \Theta(n^2) comparisons.
Divide: Sub-divide region into 4 quadrants.
4-quadrant divide
Divide: Sub-divide region into 4 quadrants.
Obstacle: Difficult to ensure n/4 points in each quadrant. So, “balanced subdivision” may be problematic.
4-quadrant obstacle
CS F364: Design & Analysis of AlgorithmsTulasimohan Molli