So Ive been working on this problem which has to do with choosing a maximal sub array with a given constraint. The problem is as follows:
Yuckdonalds is considering opening a series of restaurants along Quaint Valley Highway (QVH). The possible locations are along a straight line, and the distances of these locations from the start of QVH are, in miles and in increasing order, m1; m2; : : : ; mn
The constraints are as follows: At each location, Yuckdonalds may open at most one restaurant. The expected profit from opening a restaurant at location i is pi, where pi > 0 and i = 1;2; : : : ; n
Any two restaurants should be at least k miles apart, where k is a positive integer.
I have treated the sorted array M as a binary heap, and my algorithm consists of iterating through the binary heap for each index (in array M) and picking the max of its left/right child as long as it satisfies the distance constraint k. And then recursively calling the function with the index's left and right children.
It seems I am selecting a few optimal indices, as this is what th output suggests but I am missing something but I cant quite figure out what. PS. this is not for school, it was over a month ago and I am coding it for fun now, and I know my tempProfit variable is useless as of now
def binHandle(parent, M, P, tmp, lc):
lastchosen = lc
i = parent
left = 2*i
right = 2*i + 1
if left > len(M):
return
parent = M[parent]
if right <= len(M) and left < len(M):
childRestL = M[left]
childRestR = M[right]
#choose best child
if distance(lastchosen, childRestL) >= k:
if P[right] > P[left]:
outcome = P[right]
lastchosen = M[right]
tmp += outcome
print outcome
binHandle(right , M, P, tmp, lastchosen)
else:
outcome = P[left]
lastchosen = M[left]
tmp += outcome
print outcome
binHandle(left , M, P, tmp, lastchosen)
def maxprofits(M, P, k):
maxProf = 0
global tempProfit
tempProfit = 0
n = 1
#test each index in array
for n in range(1, len(M)):
binHandle(n, M, P, tempProfit, 0)
if tempProfit > maxProf:
maxProf = tempProfit
tempProfit = 0
return maxProf
edit: got it figured out