Been optimizing an algorithm and came down to the last part. I have an array of integers like this:
[ 1, 1, 2, 5, 0, 5, 3, 1, 1 ]
My requirement are as follows:
- input: numbers of integers to sum over
- the max sum should consist of integers next to each other
- if an integer has the value 0 the sum in the range would be invalid
- the max sum of integers and the index of each integer is returned
Expected results:
Given input of 2 (2 wanted) with the array as mentioned should therefor return [ 8, [ 5, 6 ] ] where 8 being the sum of integers at index 5 and 6
Given input of 3 (3 wanted) with the array as mentioned should therefor return [ 9, [ 5, 6, 7 ] ] where 9 being the sum of integers at index 5, 6 and 7 (notice that even though integers at indexes 3, 4, 5 have a higher sum the result is invalid due to index 4 being 0)
I'm currently managing this by doing a lot of looping, but was wondering if somebody had a better way of achieving this. My coding language of choice is currently C# - I would therefor appreciate if possible replies would be in C#. Any use of linq and other fancy Math features is ok as long as it's the fastest way.