Engineering‎ > ‎Software‎ > ‎

Algorithm

Find largest number:
public Integer findMax(int numbers[])
{
    if ( numbers == null || numbers.length == 0 ) { return null; }
    int max = numbers[0];
    for( int i = 1; i < numbers.length; ++i )
    {
        if( numbers[i] > max )
        {
            max = numbers[i];
    }    }
    return max;
}

Find largest contiguous sum and its location:
public int[] findMaxSum(int numbers[])
{
    if ( numbers == null || numbers.length == 0 ) { return new int[]{0, -1, -1}; }
    int maxSum = 0;
    int maxStartIdx = -1; int maxEndIdx = -1;
    int currentSum = 0;
    int currentStartIdx = -1;
    for( int i = 0; i < numbers.length; ++i )
    {
        if( numbers[i] <= 0 && currentSum > maxSum)
        {
            maxSum = currentSum;
            maxStartIdx = currentStartIdx; maxEndIdx = i-1;
        }
        currentSum += numbers[i];
        if( currentSum <= 0 )
        {
            currentSum = 0;
            currentStartIdx = i+1;
        }
        else if( currentSum > maxSum )
        {
            maxSum = currentSum;
            maxStartIdx = currentStartIdx; maxEndIdx = i;
        }
    }
    return new int[]{maxSum, maxStartIdx, maxEndIdx};
}

Reverse integer:
public int reverse(int input)
{
     int answer = 0;
     while(input > 0)
     {
         int digit = input % 10;
         answer = answer * 10 + digit;
         input = input/10;
     }
     return answer;
}


Comments