首页 > 代码库 > [codility]MaxProductOfThree
[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 } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。