Three Consecutive Odds

Given an integer array, return true if there are three consecutive odd numbers in the array. Otherwise, return false.

Example 1:

Input: arr = [1,2,34,3,4,5,7,23,12]
Output: true

Approach

Java

public class ThreeConsecutiveOdds {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 34, 3, 4, 5, 7, 23, 12 };
        System.out.println(threeConsecutiveOdds(arr));
    }

    static boolean threeConsecutiveOdds(int[] arr) {
        int n = arr.length;
        int cnt = 0;
        int flag = 0;
        for (int i = 0; i < n; i++) {
            if (arr[i] % 2 != 0) {
                cnt++;
                if (cnt == 3) {
                    flag = 1;
                    break;
                }
            } else {
                cnt = 0;
            }
        }
        if (flag == 1)
            return true;
        return false;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

bool threeConsecutiveOdds(vector<int> &arr)
{
    int n = arr.size();
    int cnt = 0;
    int flag = 0;
    for (int i = 0; i < n; i++)
    {
        if (arr[i] & 1)
        {
            cnt++;
            if (cnt == 3)
            {
                flag = 1;
                break;
            }
        }
        else
        {
            cnt = 0;
        }
    }
    if (flag == 1)
        return true;
    return false;
}

int main()
{
    vector<int> arr = {1, 2, 34, 3, 4, 5, 7, 23, 12};
    if (threeConsecutiveOdds(arr))
        cout << "true";
    else
        cout << "false";
    return 0;
}


No comments:

Post a Comment