codility之MaxProductOfThree

MaxProductOfThree

题目链接:

MaxProductOfThree

题目解析

比较简单, 就是求一个数组A中的三个数的乘积最大值。

如何解决?

按照题目的时间复杂度, 直接来一次排序就可以搞定了。

talk is cheap, show me the code~

代码:


function solution($A) {
    // write your code in PHP5.5
    rsort($A);
    $max = $A[0] * $A[1] * $A[2];
    $max = max($max, $A[0] * $A[count($A) - 1] *  $A[count($A) -2]);
    return  $max;
}


边界条件处理

注意到A中可能会有负数出现, 所以不能简单的用最大的三个数向乘, 在有负数的情况下是错误的。

Leave a Reply

Your email address will not be published. Required fields are marked *


To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax