LoginSignup
1
0

More than 5 years have passed since last update.

MaxProductOfThree

Last updated at Posted at 2019-01-22

名前の通り、Answer the maximum product of three numbers in the numbers! って感じの課題ですね。

1st

あれ?

Correctness Performance Task Score
50% 40% 44%
MaxProductOfThree-1.php
function solution($A) {
    rsort($A);
    return ($A[0] * $A[1] * $A[2]);
}
TestMaxProductOfThree-1.php
use PHPUnit\Framework\TestCase;
include 'MaxProductOfThree-1.php';

class TestMaxProductOfThreeTest extends TestCase {

    public function testExpect60() {
        $array = array(-3, 1, 2, -2, 5, 6);
        $ans = solution($array); $this->assertEquals(60, $ans);
    }

    public function testExpect6() {
        $array = array(1, 2, 3);
        $ans = solution($array); $this->assertEquals(6, $ans);
    }

}

例題と3値のケースは通った。
と思ったら、アホやった。

The product of triplet (P, Q, R) equates to A[P] * A[Q] * AR.

これ。全然条件満たしてなかった。やり直し。

2nd

Correctness Performance Task Score
100% 100% 100%
MaxProductOfThree-2.php
function solution($A) {
    $N = count($A);
    $product = 0;

    rsort($A);
    $max = $A[0] * $A[$N-2] * $A[$N-1];

    for($i = 2; $i < $N; $i++) {
        $product = $A[$i-2] * $A[$i-1] * $A[$i];
        if($product > $max) {
            $max = $product;
        }
    }

    return $max;
}

一回目での失敗は、例えば [-1, 5, -9, 7] という配列が与えられたとき、rsort() して先頭から
数えるだけだったため、負の数を考慮できていなかったこと。
上記の配列は rsort() すると、[7, 5, -1, -9] となるが、これを先頭から三つ乗算すると、 -35 に
なる。しかし、負の数で掛け合わせてから 7 とかけると、(-1 * -9) * 7 = 63 となる。ゆえに最大値は
63 なのだが、これを考慮出来ていなかった。
これを解決する手段として、$max の初期値を変更した。以下の通り。

- $max = $A[0] + $A[1] + $A[2];
+ $max = $A[0] * $A[$N-2] * $A[$N-1];

これが決め手となった。後者は、rsort() した後の最後の2つ、つまり最小値と二番目の最小値を意味
する。よって、その2つの値が負の数のとき、$max は正の値となり、それらの絶対値が配列の値の
すべての絶対値の中で3番以内に大きいとき、$max が求める答えになる。そうでないときは、for
ループによって正の数を三つ使い最大値を求める。
一応、Painless の問題らしいが、少し Pain を感じてしまった。まだまだコーディングのレベルが
低いんだろう。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0