Amazon Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Phone Interview
Question must be refined , its not for searching it is get any active element . The answer to this question is combination of Hashing and double linked list approach . after Much discussion i came to this answer , he accepted the answer
int MaximumContigiousSumInACircle(int *A, int *n)
{
int MaxSumInRegularArray = MaximumContigiousSum(A,n);
int MaxContigiousSumFromZeroInARun = A[0], MaxContigiousSumFromZero = 0, FirstIndex = 0;
for(int i = 1; i < n; i++)
{
if(MaxContigiousSumFromZeroInARun + A[i] > A[i])
{
MaxContigiousSumFromZeroInARun += A[i];
if(MaxContigiousSumFromZero < MaxContigiousSumFromZeroInARun)
{
MaxContigiousSumFromZero = MaxContigiousSumFromZeroInARun;
FirstIndex = i;
}
}
else
break;
}
int MaxContigiousSumFromLast = 0, MaxContigiousSumFromLastInARun = A[n - 1];
for(int i = n - 2; i >= 0 && i > FirstIndex; i--)
{
if(MaxContigiousSumFromLastInARun + A[i] > A[i])
{
MaxContigiousSumFromLastInARun += A[i];
if(MaxContigiousSumFromLastInARun > MaxContigiousSumFromLast)
MaxContigiousSumFromLast = MaxContigiousSumFromLastInARun;
}
else
break;
}
if(MaxContigiousSumFromLast + MaxContigiousSumFromZero > MaxSumInRegularArray)
return MaxContigiousSumFromLast + MaxContigiousSumFromZero;
else
return MaxSumInRegularArray;
}
int MaximumContigiousSum(int *A, int n)
{
int MaxSumInARun = A[0], MaxSum = 0;
for(int i = 1; i < n; i++)
{
if(MaxSumInARun + A[i] > A[i])
MaxSumInARun += A[i];
else
MaxSumInARun = A[i];
if(MaxSum < MaxSumInARun)
MaxSum = MaxSumInARun;
}
return MaxSum;
}
Obviously hashing can solve this issue without any doubt but I would have to answer it to be a Trie..
You can use an hashtable with key as the number itself and value the number of time it occurs. So if you want to delete a duplicate number, you can reduce the count by 1
How trie?
- dev September 30, 2011