IncompleteCoder IncompleteCoder - 3 years ago 96
Scala Question

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download