PHP Coding Challenge : Find out continuous subarray from an Array.

  • Posted on December 16, 2024
  • Technology
  • By MmantraTech
  • 67 Views

<?php
function countContinuousSubarrays($nums) {
    $n = count($nums);
    $left = 0;
    $totalSubarrays = 0;

    // Maintain the min and max elements in the current window
    $minElement = $nums[0];
    $maxElement = $nums[0];

    for ($right = 0; $right < $n; $right++) {
        // Update the min and max for the current window
        $minElement = min($minElement, $nums[$right]);
        $maxElement = max($maxElement, $nums[$right]);

        // Check if the current window is valid
        while ($maxElement - $minElement > 2) {
            $left++;
            $minElement = min(array_slice($nums, $left, $right - $left + 1));
            $maxElement = max(array_slice($nums, $left, $right - $left + 1));
        }

        // Count all subarrays ending at $right
        for ($i = $left; $i <= $right; $i++) {
            $subarray = array_slice($nums, $i, $right - $i + 1);
            echo "[" . implode(", ", $subarray) . "]\n";
        }

        $totalSubarrays += $right - $left + 1;
    }

    return $totalSubarrays;
}

// Example usage
$nums = [5, 4, 2, 4];
echo "Total Continuous Subarrays: " . countContinuousSubarrays($nums) . "\n"; // Output: 8
?>

1
Author
No Image
Admin
MmantraTech

Mmantra Tech is a online platform that provides knowledge (in the form of blog and articles) into a wide range of subjects .

You May Also Like

Write a Response