TwoSumLessThanK   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
eloc 24
c 1
b 0
f 0
dl 0
loc 40
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A twoSumLessThanK2() 0 19 4
A twoSumLessThanK() 0 17 5
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