How to find out the maximum cumulative value?

I have a file has thousands of rows and each row has a number and the number can be positive or negative. I want to do the cumulative sum from the first row. How can I find out the maximum cumulative value when I do the sum work row by row. Here is the example:

4
-3
2
-3
-1
1

In this case, the maximum cumulative value is 3 which is from adding the first 3 rows numbers (4, -3 and 2)
Thank you very much

Is this a homework assignment? Homework and coursework questions can only be posted in the homework and coursework forum with a completely filled out questionnaire from the homework rules.

If this is homework, please refile in the proper forum with a completely filled out template. If it is not homework, please explain what the purpose is for this problem.

And why do you think the maximum cumulative value is 3 when the accumulated value after reading the first line is 4?

What code have you tried to solve this problem?

What shell and operating system are you using?

This is not homework or assignment. I am doing some accounting work (many transaction) to report the highest balance on the banking account and the bank statement didn't provide the cumulative balance number to me, so I have to figure out a way to find it.
The reason I didn't count the first row because the adding work doesn't start. I don't do code work so I posted a help on this forum probably I posted the wrong place. Sorry.

Would this do?

awk '{print $1, SUM+=$1}' file3
4 4
-3 1
2 3
-3 0
-1 -1
1 0

If you need the cumulative maximum along with the line number where it occurs:

#! /bin/ksh

typeset -i iCurrLine=0
typeset -i iMaxLine=0
typeset -i iMaxSum=0
typeset -i iVal=0
typeset -i iSum=0

while read iVal ; do
     (( iCurrLine += 1 ))
     (( iSum += iVal ))
     if [ $iSum -gt $iMax ] ; then
          iMaxLine=$iCurrLine
          iMaxSum=iSum
     fi
done < /path/to/input

print - "Max Value: $iMaxSum \t occurred in line: $iMaxLine"

exit 0

Should work equally in bash.

I hope this helps.

bakunin

I'm afraid I misread your request. How about

awk '{print $1, SUM+=$1, MAX=MAX<SUM?SUM:MAX}' file