IncompleteCoder
IncompleteCoder

Reputation: 153

Scala: Find max sum of consecutive negative numbers in a List of Double

I have a List[Double] with the following values:

{-1.2200000000000006, -1.3200000000000003, -1.0099999999999998, 22.22, 11.11, 
-31.310000000000002, -0.9799999999999986,-4, -5, 3, 2, 2.959999999999999}`

I was to find the max sum of the consecutive negative numbers.

So from original list to separate consecutive lists of negative and positive

{ 
  {-1.2200000000000006, -1.3200000000000003, -1.0099999999999998},
  {22.22, 11.11},
  {-31.310000000000002, -0.9799999999999986,-4, -5},
  {3, 2, 2.959999999999999}
}

then remove the positive consecutive numbers

{ 
  {-1.2200000000000006, -1.3200000000000003, -1.0099999999999998},
  {-31.310000000000002, -0.9799999999999986,-4, -5}
}

then sum

{-3.5500000000000007, -41.29}

then change to absolute values

{3.5500000000000007, 41.29}

then find max = 41.29

Upvotes: 2

Views: 529

Answers (3)

Jeffrey Chung
Jeffrey Chung

Reputation: 19527

You could use sliding.

For sums of consecutive pairs of negative numbers:

val doubles = List(-1.2200000000000006, -1.3200000000000003, ...)
val result = doubles.sliding(2)
                    .collect { case List(a, b) if a < 0 && b < 0 => List(a, b) }
                    .map(_.sum)
                    .min
                    .abs

Upvotes: 1

jwvh
jwvh

Reputation: 51271

If you really mean to sum all the consecutive negative numbers, and then find the maximum sum, this will do it.

val nums = List(-1.2200000000000006, -1.3200000000000003, -1.0099999999999998, 
       22.22, 11.11, -31.310000000000002, -0.9799999999999986, 2.959999999999999)

nums.foldLeft(List[Double]()){
  case (l,n) if n < 0 => if (l.isEmpty) List(n) else n + l.head :: l.tail
  case (l, _) => Double.MinValue :: l
}.max
// res0: Double = -3.5500000000000007

update

OK, a minor change will get you what you're after.

nums.foldLeft(List(0.0)){
  case (l,n) if n < 0 => n + l.head :: l.tail
  case (l, _) => 0.0 :: l
}.min.abs // res0: Double = 32.29

Note: What you're actually after is the minimum sum. If you want it expressed as a positive number you can get the absolute value after the fact.

Upvotes: 1

Dima
Dima

Reputation: 40500

You can use foldLeft for that:

    val (max, _) = list.foldLeft((0,0)) { 
      case((max, current), n) if(n >= 0) => (max, 0)
      case((m, current), n) => 
         val sum = current - n
         (sum max m, sum)
     }

Upvotes: 2

Related Questions