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.
I think you can solve this in linear time. First, replace all 0s with a very small number (-2^30 for example) so that it won’t affect our sum.
Then:
You can probably avoid replacing zeros with a few extra conditions. if s[i] = sum of first i integers, then s[i] – s[k – 1] gives you the sum of the integers k through i.
Edit:
You can do this in O(1) extra space like this: first replace all 0s.
then:
To avoid replacing zeroes in the first solution, just skip k spaces ahead when encountering a zero. In the second solution, skip k or k + 1 (depends on how you choose to implement this special case) spaces ahead, but be sure to rebuild your cr variable when doing the skip!