Home > database >  Optimizing code that calculates sum of largest sequence of decreasing odd ints
Optimizing code that calculates sum of largest sequence of decreasing odd ints

Time:10-19

I wrote a method that does return sum of decreasing sequence.

For example: if sequence is 13 9 7 12 13 15, then sum is 29 (13 9 7).

Now I want to optimize it. Cause the same code is repeating muliple times. But I don't now how. Maybe someone can help me?

            int sumMax = 0;

            for (int i = 0; i < array.Length; i  )
            {
                if (i == 0)
                {
                    if (array[i] % 2 == 1)
                    {
                        sum  = array[i];

                        if (sumMax < sum)
                        {
                            sumMax = sum;
                        }
                    }
                }
                else
                {
                    if (array[i] % 2 == 0)
                    {
                        sum = 0;
                    }
                    else 
                    {
                        if (sum != 0)
                        {
                            if (array[i - 1] > array[i])
                            {
                                sum  = array[i];

                                if (sumMax < sum)
                                {
                                    sumMax = sum;
                                }
                            }
                        }
                        else
                        {
                            sum  = array[i];

                            if (sumMax < sum)
                            {
                                sumMax = sum;
                            }
                        }
                    }
                }                
            }

            return sumMax;

CodePudding user response:

Seems like a fairly simple problem. Could simply loop over the array and keep track of the current count and current max value no?

var values = new int[] {13, 9 ,7 ,12 ,13, 15};
var max = Int32.MaxValue;
var total = 0;
foreach (int value in values){
    if(value >= max)continue;
    max = value;
    total  = value;
}

This loops over every element in the array so is O(n), might be some way to make this look nicer using LINQ?

CodePudding user response:

I misread what he was asking, something like this would work instead would it not?

var values = new int[] {13, 9 ,7 ,12 ,13, 15};
int previous = int.MaxValue;
var total = 0;
var max = 0;
foreach(int value in values){
    if(value >= previous){
        if(total > max) max = total;
        total = 0;
    }
    total  = value;
    previous = value;
}
if(total > max) max = total;

Console.WriteLine(max);

You can still probabbly make this look nicer with some LINQ, but performance wise its still O(n)

  • Related