Maximum profit by buying and selling a share at most twice |  ; adding array ; 80 / 30 / / \ 25 / 15 / / \ / 2 10 / \ / 8 ; traversing through array from ( i + 1 ) th position
var price = [ 2 , 30 , 15 , 10 , 8 , 25 , 80 ] ; var profit = 0 ; for ( i = 1 ; i < price . length ; i ++ ) { var sub = price [ i ] - price [ i - 1 ] ; if ( sub > 0 ) profit += sub ; } document . write ( " " + profit ) ;