RangeSumQueryImmutable::sumRange()   A
last analyzed

Complexity

Conditions 6
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 7
c 2
b 0
f 0
dl 0
loc 12
rs 9.2222
cc 6
nc 3
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class RangeSumQueryImmutable
8
{
9
    public static function sumRange(array $nums, int $start, int $end): int
10
    {
11
        $n = count($nums);
12
        if ($n <= 0 || $start > $end || $start > $n || $end > $n) {
13
            return 0;
14
        }
15
        $ans = 0;
16
        for ($i = $start; $i <= $end; $i++) {
17
            $ans += $nums[$i];
18
        }
19
20
        return $ans;
21
    }
22
23
    public static function sumRange2(array $nums, int $i, int $j)
24
    {
25
        $n = count($nums);
26
        if ($n <= 0 || $i > $j || $i > $n || $j > $n) {
27
            return 0;
28
        }
29
30
        $helper = static function (array $map) use ($n) {
31
            for ($i = 1; $i < $n; $i++) {
32
                $map[$i] += $map[$i - 1];
33
            }
34
35
            return $map;
36
        };
37
        $map = $helper($nums);
38
39
        return $i === 0 ? $map[$j] : $map[$j] - $map[$i - 1];
40
    }
41
}
42