Suppose I have an element vector that I want to add:
a <- c(1,2,-7,5)
Here are some additional test cases:
a <- c(1,2,-3,5)
a <- c(1,2,-7,-3,5)
I know what I can use sum(a)to get the result, but what if I had a condition to keep track of:
current_sum = 0
for(i in 1:length(a)){
last_sum = current_sum
current_sum = current_sum + a[i]
if(current_sum < 0)
{
current_sum = last_sum
current_sum = current_sum + (a[i]*-1)
}
}
Here, every time the amount is negative, we return to the previous amount and add the opposite to the number that made the amount negative. Conclusion 15 as a result of the first example
Obviously, the element vector is unknown before the hand and performance problems. Is there a completely vectorized method in general or a more efficient way to do this at all (avoiding loops)?