Mandragora Program | HackerRank
Mandragora Program
The evil forest is guarded by vicious Mandragora. Garnet and her pet must make a journey through. She starts with a health point (s) and 0 experience points.
As she encounters each mandragoras, her choices are:
- Garnet’s pet eats mandragora i. This increments s by 1 and defeats mandragora.
- Garnet’s pet battles mandragora i. This increases p by s*H[i] experience points and defeats mandragora.
Once she defeats a mandragora, it is out of play. Given a list of mandragoras with various health levels, determine the maximum number of experience points she can collect on her journey.
For example, as always, she starts out with s=1 health point and p=0 experience points. Mandragoras have the following health values:h[3,2,5]. For each of the beings, she has two choices, eats or battle. We have the following permutations of choices and outcomes:
Action s p
e, e, e 4 0
e, e, b 3 15
e, b, b 2 14
b, b, b 1 10
b, b, e 2 10
b, e, e 3 9
b, e, b 2 16
e, b, e 3 6
Explanation:
There are n=3 mandragoras having the following health points: H[3,2,2]. Initially, s=1 and p=0. The following is an optimal sequence of actions for achieving the maximum number of experience points possible:
- Eat the second mandragora (H[2]=2). s is increased from 1 to 2, and p is still 0.
- Battle the first mandragora (H[1]=3). s remains the same, but p increases by s*H[1]=2*3=6experience points.
- Battle the third mandragora (H[3]=2). s remains the same, but p increases by s*H[3]=2*2=4 experience points.
Garnet earns p=6+4=10 experience points.
For further reference Mandragora program
Program:
def mandragora(H): #pass list as parameter n=len(H);d=0 for i in range(0,2**n): #loop generates all combination of binary numbers b=bin(i) #return binary value for given decimal b=b[2:] #slice the binary because binary for 1 is 0b1 c=len(b) s=1;p=0;count=0 #s->no of eats p->points m=n-c #find remaining 0's s+=m count=m m=b.count("0") #return no of 0's s+=m for j in b: if j=="1": #points are found in battles p+=s*H[count] count+=1 d=max(d,p) #return maximum of d and p return d #mandragora function returns highest point print(mandragora([3,2,2])