Passed
Push — master ( 956d7a...43c424 )
by Jinyun
02:40
created

canThreePartsEqualSum()   A

Complexity

Conditions 6
Paths 6

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 22
rs 9.2222
cc 6
nc 6
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class PartitionArrayIntoThreePartsWithEqualSum
8
{
9
    public static function canThreePartsEqualSum(array $arr): bool
10
    {
11
        if (empty($arr)) {
12
            return false;
13
        }
14
        $sum = array_sum($arr);
15
        if ($sum % 3 !== 0) {
16
            return false;
17
        }
18
        $part = $cnt = 0;
19
        foreach ($arr as $num) {
20
            $part += $num;
21
            if ($part === (int) ($sum / 3)) {
22
                $part = 0;
23
                $cnt++;
24
                if ($cnt === 3) {
25
                    return true;
26
                }
27
            }
28
        }
29
30
        return false;
31
    }
32
}
33