[codility]MaxProductOfThree

最近在学scala语言,scala代码如下:

import scala.collection.JavaConversions._
import scala.util.control.Breaks._
object Solution {
    def solution(A: Array[Int]): Int = {
        // write your code in Scala 2.10
        // many potential maximum triplets cases
        // If the maximum is positive one: 1.1 three biggest positive 1.2 two smallest negtive one biggest positive
        // If the maximum is negtive one: 1.1 three biggest negtive 1.2 two smallest positive one biggest negtive
        
        // sort
        scala.util.Sorting.quickSort(A)
        // get all the possible maximum ang keep record of the global maximum
        var result: Int = -1000000000
        result = scala.math.max(result, A(A.length-1)*A(A.length-2)*A(A.length-3))
        result = scala.math.max(result, A(0)*A(1)*A(A.length-1))
        var firstPositiveIndex: Int = 0
        breakable {
            for(firstPositiveIndex <- 0 to A.length-1) {
                if(A(firstPositiveIndex) >= 0) break
            }
        }
        if(firstPositiveIndex-3 >= 0)
            result = scala.math.max(result, A(firstPositiveIndex-1)*A(firstPositiveIndex-2)*A(firstPositiveIndex-3))
        if(firstPositiveIndex-1 >= 0 && firstPositiveIndex+1 < A.length)
            result = scala.math.max(result, A(firstPositiveIndex-1)*A(firstPositiveIndex)*A(firstPositiveIndex+1))
        
        result
    }
}


你可能感兴趣的:([codility]MaxProductOfThree)