lundi 4 novembre 2019

how to further optimise this problem using Dynamic programming or any other optimisation technique

mandrake the magician has decided to distribute his wealth among his best friends lothar and magnon,Now he has N coins each having some value A[i] (i<=i<=N) being a great magician mandrake can change the value of coins except the first and the last one He can change the value of ith coin to half of sum of (i-1 )th and (i+1)th coin but for doing so two condition need to befulfilled

1-value of both i-1 and i+1 coin should be even and 2-if jth coin value is changed after ith coin value then j>i

Now he will distribte his wealth such that he will give one coin from the back to lothar and one coin from the front to magnon simultaneously Hwill continue this until all the coins he owns are distributed Consider that in case of odd number of coins he will give his middle most coin to other friend thero he wishes to maximise the absolute difference of value of coins given to lothar and Magnon

example-> 10

5 6 5 2 1 7 9 7 2 5

these are multiple cases for the coin values based on magician rules 1.5 6 5 2 1 7 9 7 2 5 2.5 6 4 2 1 7 9 7 2 5

absulute difference case1- |5-5|+|6-2|+|5-7|+|2-9|+|1-7|=19 absolute difference case 2=|5-5|+|6-2|+|4-7|+|2-9}+|1-7|=20 so answer is 20

i have tried the below approach but the compiler is asking me to further optimise it .I think dynamic programming can be used but couldn't able to figure out any subproblem that is being repeated .Can anyone help?

#include<bits/stdc++.h>
using namespace std;
int helper(int *l,int j,int n)
{/*
int l[n];
for(int i=0;i<n;i++)
{
l[i]=input[i];
}*/

if(j==n)
{
int sum=0;
int k=0;
while(k<n/2)
{
sum+=abs(l[k]-l[n-1-k]);
k++;
}

return sum;
}




int nc=helper(l,j+1,n);
int c=0;
if(j-1>=0 && j+1<n &&(l[j-1]%2==0&& l[j+1]%2==0))
{
    l[j]=(l[j+1]+l[j-1])/2;
    int c=helper(l,j+1,n);

}

int b=max(c,nc);
return b;




}


int main()
{
    int a[10]={5,6,5,2,1,7,9,7,2,5};
    cout<<helper(a,0,10)+1;
    /*for(int i=0;i<1000;i++)
    {

        memo[i]=-1;
    }*/
}
enter code here

Aucun commentaire:

Enregistrer un commentaire