Interview Question
Software Engineer / DevelopersCan anyone check please this code? Thanks!
int lowestCost(int N,int* a, int left, int right)
// a is the array of the number of characters in each segment, in the example it is [2,6,2,10]
// left and right are the indices of array a, a[left]+a[left+1]+...+a[right-1]+a[right] should = N
{
int min=999999;
for(int i=left;i<=right-1;i++)
{
int costsFromLeft=0;
int costsFromRight=0;
cout<<"i="<<i<<endl;
if(i>left)
{
int sumLeft=0;
for(int j=left;j<=i;j++)
sumLeft+=a[j];
cout<<"cutting "<<sumLeft<<" from:"<<left<<" to:"<<i<<endl;
costsFromLeft=lowestCost(sumLeft,a,left,i);
}
if(right>i+1)
{
int sumRight=0;
for(int j=i+1;j<=right;j++)
sumRight+=a[j];
cout<<"cutting "<<sumRight<<" from:"<<i+1<<" to:"<<right<<endl;
costsFromRight=lowestCost(sumRight,a,i+1, right);
}
if(costsFromLeft+costsFromRight<min)
min=costsFromLeft+costsFromRight;
}
return min+N;
}
To start, we call
int l=lowestCost(N,a,0,length_of_a-1);
(It should be easy to convert L to a)
Can anyone check please this code? Thanks!
- Anonymous October 15, 2010int lowestCost(int N,int* a, int left, int right)
// a is the array of the number of characters in each segment, in the example it is [2,6,2,10]
// left and right are the indices of array a, a[left]+a[left+1]+...+a[right-1]+a[right] should = N
{
int min=999999;
for(int i=left;i<=right-1;i++)
{
int costsFromLeft=0;
int costsFromRight=0;
cout<<"i="<<i<<endl;
if(i>left)
{
int sumLeft=0;
for(int j=left;j<=i;j++)
sumLeft+=a[j];
cout<<"cutting "<<sumLeft<<" from:"<<left<<" to:"<<i<<endl;
costsFromLeft=lowestCost(sumLeft,a,left,i);
}
if(right>i+1)
{
int sumRight=0;
for(int j=i+1;j<=right;j++)
sumRight+=a[j];
cout<<"cutting "<<sumRight<<" from:"<<i+1<<" to:"<<right<<endl;
costsFromRight=lowestCost(sumRight,a,i+1, right);
}
if(costsFromLeft+costsFromRight<min)
min=costsFromLeft+costsFromRight;
}
return min+N;
}
To start, we call
int l=lowestCost(N,a,0,length_of_a-1);
(It should be easy to convert L to a)