My recursive scala solution


  • 0
    S
    object Solution {
        def maxProduct(nums: Array[Int]): Int = {
            if (nums == null || nums.size == 0) {
                return 0;
            }
            val list: List[Int] = nums.toList
            val head: Int = list.head
            val tail: List[Int] = list.tail
            _MaxProduct(tail, head, head, head)
        }
        
        def _MaxProduct(nums: List[Int], min: Int, max: Int, result: Int): Int = nums match {
            case Nil => result
            case x :: xs => {
                val cur_min = math.min(x, math.min(x * max, x * min))
                val cur_max = math.max(x, math.max(x * max, x * min))
                _MaxProduct(xs, cur_min, cur_max, math.max(cur_max, result))
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.