Precomputing the number of 1 s
let ones = new Array ( R + 1 ) ; for ( var i = 0 ; i < ones . length ; i ++ ) { ones [ i ] = new Array ( 2 ) ; } for ( var i = 0 ; i < ones . length ; i ++ ) { for ( var j = 0 ; j < ones . length ; j ++ ) { ones [ i ] [ j ] = 0 ; } } for ( let i = 1 ; i <= R ; i ++ ) for ( let j = 1 ; j <= C ; j ++ ) { if ( mat [ i - 1 ] [ j - 1 ] == 1 ) val = 1 ; ones [ i ] [ j ] = ones [ i - 1 ] [ j ] + ones [ i ] [ j - 1 ] - ones [ i - 1 ] [ j - 1 ] + ( val ) ; }