Monday, March 29, 2010

03/29: Interview Question

 

Question :

You are given an array of integers (both positive and negative). Find the continuous sequence with the largest sum. Return the sum.
EXAMPLE
input: {2, -8, 3, -2, 4, -10}
output: 5 [ eg, {3, -2, 4} ]

Answer :

public int GetMaxSumFromArray()

{

int maxsum;

int tempsum;

int [] a=new int[]{6, -8, 3, -2, 4,-10};

for (int i=1;i<=n;i++)

{

tempsum+=tempsum+a[i];

if (tempsum<0)

// if tempsum<0

 

{

tempsum=0;

}

//since the array has positive value, so maxsum can not be 0 , so the smallest value is 0

 

if(maxsum<tempsum)

{

maxsum=tempsum

}

}

return maxsum;

}

}

0 Comments:

Post a Comment

<< Home