码迷,mamicode.com
首页 > 其他好文 > 详细

[codility]MaxProductOfThree

时间:2014-05-04 09:42:56      阅读:372      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   get   

最近在学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,布布扣,bubuko.com

[codility]MaxProductOfThree

标签:style   blog   class   code   java   get   

原文地址:http://blog.csdn.net/sunbaigui/article/details/24937733

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!