6.006 Final Exam Solutions
Name
2
Problem 2.
Storing Partial Maxima
[30 points]
(1 part)
6.006 student, Mike Velli, wants to build a website where the user can input a time interval in
history, and the website will return the most exciting sports event that occurred during this interval.
Formally, suppose that Mike has a chronologically sorted list of
n
sports events with associated
integer “excitement factors”
e
1
, . . . , e
n
. You can assume for simplicity that
n
is a power of
2
. A
user’s query will consist of a pair
(
i, j
)
with
1
≤
i < j
≤
n
, and the site is supposed to return
max(
e
i
, e
i
+1
, . . . , e
j
)
.
Mike wishes to minimize the amount of computation per query, since there will be a lot of traffic
to the website. If he precomputes and stores
max(
e
i
, . . . , e
j
)
for every possible input
(
i, j
)
, he can
respond to user queries quickly, but he needs storage
Ω(
n
2
)
which is too much.
In order to reduce storage requirements, Mike is willing to allow a small amount of computation
per query. He wants to store a cleverer selection of precomputed values than just
max(
e
i
, . . . , e
j
)
for every
(
i, j
)
, so that for any user query, the server can retrieve two precomputed values and take
the maximum of the two to return the final answer. Show that now only
O
(
n
log
n
)
values need to
be precomputed.
Solution:
We are given the list
e
1
, . . . , e
n
. For each
1
≤
i
≤
n/
2
, store
max(
e
i
, e
i
+1
, . . . , e
n/
2
)
,
and for each
n/
2
< j
≤
n
, store
max(
e
n/
2+1
, . . . , e
j
)
.
Recurse separately on the two lists
e
1
, . . . , e
n/
2
and
e
n/
2+1
, . . . , e
n
. Stop the recursion when the list size becomes
1
.
If the user’s query is
(
i, j
)
with
i
≤
n/
2
and
j > n/
2
, then we can return
max(max(
e
i
, e
i
+1
, . . . , e
n/
2
)
,
max(
e
n/
2+1
, . . . , e
j
))
. If both
i, j
≤
n/
2
or
i, j > n/
2
, then the answer is found recursively.
Let
S
(
n
)
be the number of values stored for a list of length
n
. By construction,
S
(
n
) =
O
(
n
) +
2
S
(
n/
2)
, and therefore,
S
(
n
) =
O
(
n
log
n
)
.