Flags::getMaxFlags()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 1
eloc 9
nc 1
nop 2
1
<?php
2
3
namespace Lesson08;
4
5
class Flags
6
{
7
    public function solution($A)
8
    {
9
        $arrayCount = count($A);
10
        $peaks = [];
11
        for ($i = 1; $i < $arrayCount - 1; $i++) {
12 View Code Duplication
            if ($A[$i] > $A[$i - 1] && $A[$i] > $A[$i + 1]) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
13
                $peaks[] = $i;
14
            }
15
        }
16
        $numberOfPeaks = count($peaks);
17
18
        $maxFlags = $this->getMaxFlags($arrayCount, $numberOfPeaks);
19
20
        for ($flags = intval($maxFlags); $flags > 0; $flags--) {
21
            $remainingFlags = $flags;
22
            $previousPeak = null;
23
            $currentPeak = 0;
24
            while ($currentPeak < $numberOfPeaks && $remainingFlags > 0) {
25
                if ($previousPeak === null || $peaks[$currentPeak] - $peaks[$previousPeak] >= $flags) {
26
                    $remainingFlags--;
27
                    $previousPeak = $currentPeak;
28
                }
29
                $currentPeak++;
30
            }
31
            if ($remainingFlags == 0) {
32
                return $flags;
33
            }
34
        }
35
36
        return 0;
37
    }
38
39
    /**
40
     * @param $arrayCount
41
     * @param $numberOfPeaks
42
     *
43
     * @return mixed
44
     */
45
    private function getMaxFlags($arrayCount, $numberOfPeaks)
46
    {
47
        $quadraticCoefficient = 1;
48
        $linearCoefficient = -1;
49
        $constant = -($arrayCount - 1);
50
        $numerator = $linearCoefficient * $linearCoefficient - 4 * $quadraticCoefficient * $constant;
51
        $firstX = (-$linearCoefficient + sqrt($numerator)) / (2 * $quadraticCoefficient);
52
        $secondX = (-$linearCoefficient - sqrt($numerator)) / (2 * $quadraticCoefficient);
53
        $maxFlags = min($numberOfPeaks, max($firstX, $secondX));
54
55
        return $maxFlags;
56
    }
57
}
58