Best Algorithm Homework Help 1
Best Algorithm Homework Help 1
Representative Zena Torr is facing off against Senator Kong Grossman in a heated
presidential primary: a sequence of n head-to-head state contests, one per day for n days.
Each state contest i ∈ {1, . . . , n} has a known positive integer delegate count di, and a
projected delegate count zi < di that Rep. Torr would win if she took no further action.
There are total delegates and Rep. Torr needs at least delegates to win.
Unfortunately, Rep. Torr is projected to lose the race, since
so she needs to take action. Rep. Torr has a limited but effective election team which can
campaign in at most one state per day. If the team campaigns on day i, they will win all di
delegates in state i, but they will not be able to campaign at all for two days after day i, as
it will take time to relocate. Describe an O(n)-time algorithm to determine whether it is
possible for Rep. Torr to win the primary contest by campaigning effectively.
Solution:
1. Subproblems
• x(i): max delegates Torr can win in states i to n, where campaign on day i is possible
• for i ∈ {1, . . . , n + 1}
programminghomeworkhelp.com
2. Relate
3. Topo
4. Base
5. Original
programminghomeworkhelp.com
6. Time
• # subproblems: n + 1
• Work per subproblem: O(1)
• O(n) running time
Ting Kiger is an eccentric personality who owns n pet tigers and n 2 cages.
programminghomeworkhelp.com
• Each tiger i has known positive integer age ai and size si (no two have the same age or
size).
• Each cage j has known positive integer capacity cj and distance dj from Ting’s bedroom
(no two have the same capacity or distance).
• Ting favors older tigers and wants them to sleep closer to his bedroom, i.e., any two
tigers x and y with ages ax < ay must be assigned to cages X and Y respectively such that
dY < dX.
• A tiger i assigned to cage cj will experience positive discomfort si - cj if si > cj , but will
not experience any discomfort if
Describe an O(n3)-time algorithm to assign tigers to cages that favors older tigers and
minimizes the total discomfort experienced by the tigers.
Solution: The “favors older tigers” condition ensures that the tigers sorted decreasing by
age will be matched with a subsequence of the cages sorted increasing by distance from
Ting’s bedroom. So first sort the tigers into sequence T decreasing by age in O(n log n)
time and the cages into sequence C increasing by distance in O(n2 log n) time (e.g., via
merge sort). Now, we use dynamic programming to find an optimal matching from T with
a subsequence of C.
programminghomeworkhelp.com
1. Subproblems
• x(i, j) : min total discomfort possible, matching tigers T[i :] to a subsequence of C[j :]
for i ∈ {0, . . . , n} and j ∈ {0, . . . , n2}
2. Relate
• Can either match tiger T[i] with cage C[j] or not. Guess!
• If matched, incur discomfort of match (if any).
• In either case, won’t match C[j] with any tiger in T[i + 1 :] so recurse on remainder
• Let d(i, j) be the discomfort of matching tiger T[i] with cage C[j]
• i.e., d(i, j) = si - cj if si > cj and zero otherwise
• x(i, j) = min{d(i, j) + x(i + 1, j + 1), x(i, j + 1)}
3. Topo
4. Base
programminghomeworkhelp.com
5. Original
6. Time
Given a weighted directed acyclic graph G = (V, E,w) with integer weights and two
vertices s,t ∈ V , describe a linear-time algorithm to determine the number of paths
from s to t having odd weight. When solving this problem, you may assume that a
single machine word is large enough to hold any integer computed during your
algorithm.
Solution: The number of paths from s to t having odd weight, depends on the number of
paths to each of t’s incoming neighbers: paths of odd weight if the incoming edge is
programminghomeworkhelp.com
even, and paths of even weight if the incoming edge is odd. So we make two types of
subproblem per vertex representing the number of even weight and odd weight paths to
the vertex.
1. Subproblems
• x(v, i): the number of paths from s to v, having even weight if i = 0 and odd weight if i =
1
• for all v ∈ V and i ∈ {0, 1}
2. Relate
• In a DAG, the number of even or odd paths to v is the sum of the relevant paths to its
incoming vertices
• Let p(i) be the parity of integer i, i.e., p(i) = 0 if i is even and p(i) = 1 if i is odd P
• x(v, i) = {x(u, p(w(u, v) + i)) | u ∈ Adj-(v)}
3. Topo
• x(v, i) depends only on subproblems x(u, j) for vertices u that appear earlier in the
topological order of G, so acyclic
programminghomeworkhelp.com
4. Base
5. Original
6. Time
• # subproblems: 2|V |
• Work per subproblem: O(deg-v))
O(2 ∑vЄV deg –(v)) = O(|V | + |E|) running time (linear in the size of the graph)
Liza Pover and her little brother Lie Pover want to share a round pizza pie that has been
cut into 2n equal sector slices along rays from the center at angles αi = iπ/n for i ∈ {0,
1, . . . , 2n}, where α0 = α2n. Each slice i between angles αi and αi+1 has a known integer
programminghomeworkhelp.com
tastiness ti (which might be negative). To be “fair” to her little brother, Liza decides to eat
slices in the following way:
• They will each take turns choosing slices of pizza to eat: Liza starts as the chooser.
• If there is only one slice remaining, the chooser eats that slice, and eating stops.
– Angle αi is proper if there is at least one uneaten slice on either side of the line passing
through the center of the pizza at angle αi.
– The chooser picks any number i ∈ {1, . . . , 2n} where αi is proper, and eats all uneaten
slices counter-clockwise around the pizza from angle αi to angle αi + π.
– Once the chooser has eaten, the other sibling becomes the chooser, and eating
continues.
Liza wants to maximize the total tastiness of slices she will eat. Describe an O(n3)-time
algorithm to find the maximum total tastiness Liza can guarantee herself via this
selection process.
programminghomeworkhelp.com
Solution: As the siblings eat pizza, the uneaten slices are always cyclically consecutive
(since removal of a half plane is a convex operation). So we choose consecutive cyclic
subarrays as our subproblems. Each sibling wants to maximize tastiness, we make
different subproblems based on which sibling is currently the chooser.
While making choices, it will be useful to know the tastiness of any subarray. Let v(i, j)
be the tastiness of the j slices counter-clockwise from angle αi, i.e., v(i, j) = ∑ j-1 k=0 ((i+k)
mood 2n) , where indices are taken modulo 2n, for i ∈ {0, . . . , 2n - 1} and j ∈ {0, . . . , n}.
There are O(n2) such v(i, j) and each can be computed na¨ıvely in O(n) time, O(n 3) time
in total. Note that these can also be computed in O(n 2) time via dynamic programming,
but the na¨ıve method is sufficient for the requested time bound.)
1. Subproblems
• x(i, j, p) : the maximum tastiness Liza can acheive with the j slices counter-clockwise
from αi remaining, when either: Liza is the chooser when p = 1, or Lie is the chooser
when p = 2
• for i ∈ {0, . . . , 2n - 1}, j ∈ {0, . . . , n}, p ∈ {1, 2}
• (we can only have at most n slices after first choice, so we don’t compute for j > n2.
Relate
• Liza tries to maximize, while Lie may try to minimize (so in worst case he does)
• Chooser can choose any proper angle and then choose a side. Guess!
• Angle αi+k is proper for any k ∈ {1, . . . , j - 1}
• Chooser eats either: k slices between αi and αi+k or j -k slices between αi+k and αi+j
• Liza does not gain or lose tastiness when Lie eats
}
k∈ {1, . . . , j - 1}
}
v(i + k, j - k) + x(i, k, 2)
x(i, k, 1)
programminghomeworkhelp.com
3. Topo
4. Base
5. Original
6. Time
programminghomeworkhelp.com
Problem 7-5. Shorting Stocks
Bordan Jelfort is a short seller at a financial trading firm. He has collected stock price
information from s different companies C = (c0, . . . , cs-1) for n consecutive days. Stock
price information for a company ci is a chronological sequence Pi = (p0, . . . , pnk-1) of nk
prices, where each price is a positive integer and prices {pkj , . . . , pkj+k-1} all occur on
day j for j ∈ {0, . . . , n - 1}. The shorting value of a company is the length of the longest
chronological subsequence of strictly decreasing prices for that company that doesn’t skip
days: if the sequence contains two prices on different days i and j with i < j, then the
sequence must also contain at least one price from every day in {i, . . . , j}.
(a) Describe an O(snk2)-time algorithm to determine which company ci has the highest
shorting value, and return a longest subsequence S of decreasing subsequences of prices
from Pi that doesn’t skip days.
Solution: We will compute the shorting value of each company via dynamic programming
(assuming P = Pi), and then return the longest in O(s) time.
1. Subproblems
• x(j): the longest decreasing subsequence of prices that doesn’t skip days in P[j :] that
includes price P[j]
programminghomeworkhelp.com
• for j ∈ {0, . . . , nk - 1}
2. Relate
• Next in sequence has price at later time in same day or the next day. Guess!
• At price index j, there are (k - 1) - (j mod k) prices left in same day
• Then there are k prices in the following day (if it exists)
• So last next price index is f(j) = min{j + (k - 1) - (j mod k) + k, nk - 1}
• x(j) = 1 + max{x(d) | d ∈ {j + 1, . . . , f(j)} and P[j] > P[d]} ∪ {0}
3. Topo
4. Base
5. Original
programminghomeworkhelp.com
• Solve subproblems via recursive top down or iterative bottom up
• Shorting value is max max nk-1 x(j)
j=0
6. Time
• # subproblems: nk
• Work per subproblem: O(k)
• Work for original: O(nk)
• O(nk2) running time
(b) Write a Python function short company(C, P, n, k) that implements your algorithm
from part (a) using the template code provided. You can download the code template and
some test cases from the website.
Solution:
1 # iterative bottom-up
2 def short_company(C, P, n, k):
3 S=[ ]
programminghomeworkhelp.com
4 for i in range(len(C)):
5 p = P[i]
6 x = [1 for _ in range(n*k)] # subproblem memo
7 r = [None for _ in range(n*k)] # parent pointer memo
8 best = 0
9 for j in range(n*k - 1, -1, -1): # compute memos
10 f = min(j + (k - 1) - (j % k) + k, n*k - 1)
11 for d in range(j + 1, f + 1):
12 if (p[j] > p[d]) and (1 + x[d] > x [ j ]):
13 x[j] = 1 + x[d]
14 r[j] = d
15 if x[best] < x[ j ]:
16 best = j
17 if x[best] > len(S): # reconstruct from parent pointers
18 c, S = C[i], []
19 while best != None:
20 S.append(p[best])
21 best = r[best]
22 S = tuple(S)
23 return (c, S)
programminghomeworkhelp.com
1 # recursive top-down
2 def short_company(C, P, n, k):
3 S = []
4 for i in range(len(C)):
5 p = P[i]
6 memo = [None for _ in range(n*k)] # memo for subproblems and parents
7 def dp(j): # recursive function
8 if memo[j] is None:
9 F = min(j + (k - 1) - (j % k) + k, n*k - 1)
10 x, r = 1, None
11 for d in range(j + 1, f + 1):
12 x_, _ = dp(d)
13 if (p[j] > p[d]) and (1 + x_ > x):
14 x, r = 1 + x_, d
15 memo[j] = (x, r)
16 return memo[j]
17 best, opt = 0, 0
18 for j in range(n*k):
19 x, _ = dp(j)
20 if x > opt:
programminghomeworkhelp.com
20 best, opt = j, x
21 if opt > len(S): # reconstruct from parent pointers
22 c, S = C[i], []
23 while best != None:
24 S.append(p[best])
25 _, best = dp(best)
26 S = tuple(S)
27 return (c, S)
programminghomeworkhelp.com