1550. Three Consecutive Odds #285
-
Topics: Given an integer array Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem asks us to determine if an array contains three consecutive odd numbers. If such a triplet exists, return Key Points
ApproachWe need to iterate through the array and check every triplet of consecutive numbers to see if they are all odd. If we find such a triplet, we can immediately return Plan
Let's implement this solution in PHP: 1550. Three Consecutive Odds <?php
/**
* @param Integer[] $arr
* @return Boolean
*/
function threeConsecutiveOdds($arr) {
// Iterate through the array, checking each triplet
for ($i = 0; $i < count($arr) - 2; $i++) {
// Check if the current number and the next two numbers are odd
if ($arr[$i] % 2 != 0 && $arr[$i + 1] % 2 != 0 && $arr[$i + 2] % 2 != 0) {
// If all three are odd, return true
return true;
}
}
// If no such triplet is found, return false
return false;
}
// Example usage:
$arr1 = [[15, 96], [36, 2]];
$arr2 = [[1, 3, 5], [4, 1, 1], [1, 5, 3]];
$arr3 = [[2, 5, 1], [3, 4, 7], [8, 1, 2], [6, 2, 4], [3, 8, 8]];
echo threeConsecutiveOdds($arr1) . "\n"; // Output: 17
echo threeConsecutiveOdds($arr2) . "\n"; // Output: 4
echo threeConsecutiveOdds($arr3) . "\n"; // Output: 10
?> Explanation:
Example WalkthroughExample 1:Input:
Output: Example 2:Input:
Output: Time Complexity
Overall Time Complexity: O(n) Output for Example
The solution efficiently identifies three consecutive odd numbers by iterating through the array once. It utilizes a straightforward condition to determine odd parity and exits early when a valid triplet is found, minimizing unnecessary checks. The approach is optimal for the problem's constraints. |
Beta Was this translation helpful? Give feedback.
The problem asks us to determine if an array contains three consecutive odd numbers. If such a triplet exists, return
true
; otherwise, returnfalse
.Key Points
arr
) where each element satisfies 1 \leq arr[i] \leq 1000.Approach
We need to iterate through the array and check every triplet of consecutive numbers to see if they are all odd. If we find such a triplet, we can immediately return
true
. If we traverse the entire array without finding one, returnfalse
.