scala - MaxSubArray using dynamic style -


i have been trying create code counts max substring array , returns sum , starting , ending point. have error in there cannot spot because example when use array(-2, 1, -3, 4, -1, 2, 1, -5, 4) source return (7, 5,8). however, correct answer should (6, 3, 6). code below.

 def solve(a: array[int]): (int, int, int) = {     require(a.nonempty)      val n = a.length     val temp = array.fill(n)(0, 0, 0)     var max = (0,0,0)                      // sum, start, end      (i <- 0 n-1) {       temp(i) = (a(i), i, i)     }      (i <- 0 n-1) {       (j <- 0 i) {         if (a(i) > a(j) && temp(i)._1 < temp (j)._1 + a(i)) {           temp(i) = (temp(j)._1 + a(i), j, i)          }       }     }     (i <- 0 n-1){       if (max._1 < temp(i)._1){         max = temp(i)            }     }     return max  } 

how more scala/functional approach?

  def solve(a: array[int]): (int, int, int) = {     a.tails.zipwithindex.flatmap{       case (arr, ti) =>         arr.inits.map{           tail => (tail.sum, ti, ti + tail.length -1)         }     }.maxby(_._1)   }  solve (array(-2, 1, -3, 4, -1, 2, 1, -5, 4)) => res7: (int, int, int) = (6,3,6) 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -