We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
importjava.util.Scannerimportscala.collection.immutable.QueueobjectSolution{defmain(args:Array[String]):Unit={valsc=newScanner(System.in)sc.nextIntvalk=sc.nextIntsc.nextLinevala=sc.nextLine.split(" ").map(_.toInt)sc.close()caseclassAcc(list:List[Int])valsentinel=Int.MaxValue/2valtemp=a.foldLeft(Acc(List(-sentinel,sentinel)))((acc,v)=>acc.listmatch{caseNilifv<0=>acccaseNil=>Acc(v::Nil)caselist@x::xs=>if((v<0)==(x<0))Acc(x+v::xs)elseAcc(v::list)}).listvalcompressed=if(temp.head<0)temp.tailelsetempprintln(solve(compressed).sortBy(-_).take(k).mkString("\n"))}defsolve(seq:List[Int]):List[Int]={caseclassAccumulator(totalSum:Int,queue:Queue[Int],answer:List[Int])@scala.annotation.tailrecdefinner(seq:List[Int],acc:Accumulator):List[Int]={seqmatch{caseNil=>acc.answercasexPos::xsifacc.queue.isEmpty=>//empty queueinner(xs,Accumulator(xPos,Queue(xPos),acc.answer))casexNeg::xPos::xs=>val(nextSeq,nextAcc)={valsNeg=acc.totalSum+xNegif(sNeg<=0){val(firstPos,tempQueue)=acc.queue.dequeueif(tempQueue.isEmpty){//All items in queue are processed.(xs,Accumulator(xPos,Queue(xPos),firstPos::acc.answer))}else{if(acc.totalSum>=firstPos){//Glue items in queue.(xs,Accumulator(xPos,Queue(xPos),acc.totalSum::acc.answer))}else{//Separate first item in queue.val(_,nextQueue)=tempQueue.dequeue(nextQueue.toList++seq,Accumulator(0,Queue(),firstPos::acc.answer))}}}else{valsPos=sNeg+xPosif(sPos>=acc.queue.head){//Glue(xs,Accumulator(sPos,Queue(sPos),acc.answer))}else{//Uncertain(xs,Accumulator(sPos,acc.queue.enqueue(xNeg).enqueue(xPos),acc.answer))}}}inner(nextSeq,nextAcc)}}inner(seq,Accumulator(0,Queue(),Nil))}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Order exercises
You are viewing a single comment's thread. Return to all comments →