I need help with c# algorithm


#1

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;
 
}


#2

try looking at the forums on www.canyoudomyhomeworkforme.com


#3

All I was asking for was help on my algorithm, I obviously tried given that I posted my code. You make it sound like I give my entire assignment to the forums to be done for me. This is only a minute part of my assignment and I’m stuck. Anyway, thanks for the help.


#4

lol - and there was me actually clicking on the link (purely out of interest, you understand…) :wink:


#5

Me too hehe 8)
Curiosity killed the cat


#6

your link seems to be broken…

:wink:

Simon


#7

It looks to me as if (and I could be missing something) that you aren’t resetting your gainsSoFar when you hit a negative gain.


#8

This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.