Neighbors of the same sign#7844

Neighbors of the same sign (Editorial)

Let's read the input sequence of numbers into the array m. Then, using a loop, we will output pairs of adjacent elements of the same sign. A pair of elements m_i and m_{i+1} have the same sign if their product is positive: m_i * m_{i+1} > 0.

Algorithm Implementation

Declare the working array.

int m[101];

Read the number of input numbers n.

scanf("%d", &n);

Read the input array.

for (i = 0; i < n; i++)
    scanf("%d", &m[i]);

Output pairs of adjacent elements of the same sign.

for (i = 0; i < n - 1; i++)
    if (m[i] * m[i + 1] > 0)
        printf("%d %d\n", m[i], m[i + 1]);

Java Implementation

import java.util.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner con = new Scanner(System.in);
        int n = con.nextInt();
        int m[] = new int[n];
        for(int i = 0; i < n; i++)
            m[i] = con.nextInt();
        for(int i = 0; i < n - 1; i++)
            if (m[i] * m[i+1] > 0) 
                System.out.println(m[i] + " " + m[i+1]);
        con.close();
    }
}

Python Implementation

n = int(input())
lst = list(map(int, input().split()))
for i in range(n - 1):
    if lst[i] * lst[i+1] > 0: print(lst[i], lst[i+1])