TwoSumLessThanK::twoSumLessThanK()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 17
rs 9.6111
cc 5
nc 5
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class TwoSumLessThanK
8
{
9
    public static function twoSumLessThanK(array $nums, int $k): int
10
    {
11
        $ans = -1;
12
        if (empty($nums)) {
13
            return $ans;
14
        }
15
        $n = count($nums);
16
        for ($i = 0; $i < $n; $i++) {
17
            for ($j = 1; $j < $n; $j++) {
18
                $sum = $nums[$i] + $nums[$j];
19
                if ($sum < $k) {
20
                    $ans = max($ans, $sum);
21
                }
22
            }
23
        }
24
25
        return $ans;
26
    }
27
28
    public static function twoSumLessThanK2(array $nums, int $k): int
29
    {
30
        $ans = -1;
31
        if (empty($nums)) {
32
            return $ans;
33
        }
34
        sort($nums);
35
        [$ans, $l, $r] = [-1, 0, count($nums) - 1];
36
        while ($l <= $r) {
37
            $sum = $nums[$l] + $nums[$r];
38
            if ($sum < $k) {
39
                $ans = max($ans, $sum);
40
                $l++;
41
            } else {
42
                $r--;
43
            }
44
        }
45
46
        return $ans;
47
    }
48
}
49