Hi guys, I am trying to find the best possible period in a given array filled with random doubles including negative numbers.
each number in the array represents a daily stock gain(loss). And the array size is 365 representive of the number of days in a year. My goal is to loop trough this array and find the best period (sequence of numbers that add up to the highest) within the array. I am having difficulty coming up with an algorithm and was wondering if anyone here may be of help. Thanks.
Here is my code, but it doesnāt work right, I get something like 7390 when I am suppose to get 1440. I can provide the txt file with the numbers in the array if you like.
private double calculateBestGainsPeriod()
{
double[] mydailyGains = this.dailyGains;
double possibleGain=0.0;
double gainsSoFar=0.0;
for(int i = 0; i < dailyGains.Length; i++)
{
if(dailyGains[i] > 0)
{
gainsSoFar+= dailyGains[i];
}
else if(dailyGains[i] < 0 && i < dailyGains.Length-1)
{
//negativeGain = dailyGains[i];
possibleGain = gainsSoFar + dailyGains[i] + mydailyGains[i+1];
if(possibleGain > gainsSoFar)
{
gainsSoFar = possibleGain;
}
possibleGain = 0;
i++;
}
}
return gainsSoFar;
}
