Karthik Selvakumar Bhuvaneswaran is a Software Engineer working on Saas(RoR) and PaaS(Salesforce.com) applications. He beleives on day starts at night and requires nothing more than Music, a cup of cofee and a fully charged laptop.
Array - Maximum Subsequence with start and end of index
arr=[-1,1,2,-1,8,-3,5,7,-4,-2,9,-2,4,-5]start=0ending=0maxsofar=0maxendinghere=0defmax(i,j)ifi>jreturnielsereturnjendendarr.each_with_indexdo|val,i|maxendinghere=max(maxendinghere+val,0)ifmaxendinghere>maxsofarending=imaxsofar=maxendinghereendendsum=0# Backtrack to find the start # Another n traversal => 2n :: O(n)(0..ending).to_a.eachdo|from_end|sum+=arr[ending-from_end]ifsum==maxsofarstart=arr.length-from_endendendp" starting from index: #{start}"p" ending at index: #{ending}"p"Maximum sum is: #{maxsofar}"# Output:#" starting from index: 3"#" ending at index: 12"#"Maximum sum is: 24"