Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class longestAlternating {
- public static void calculateLongestAlternating(int arr[]) {
- int n = arr.length;
- // loop through elemnts in array
- for (int i=0; i < n; i++) {
- int numberOfAlternating = 1;
- // loop through elements in sub array
- for (int j = i; j < n-1; j++) {
- int multiple = arr[j] * arr[j + 1];
- // check if multiple is negative
- if (multiple < 0) {
- numberOfAlternating = numberOfAlternating + 1;
- } else {
- break;
- }
- }
- System.out.print("For index: " + i + " {");
- for (int k = i; k < arr.length; k++) {
- if (k > 0) {
- System.out.print(" ");
- }
- System.out.print(arr[k]);
- }
- System.out.println("} = " + numberOfAlternating);
- }
- }
- public static void main(String[] args) {
- // int array[] = {1, -5, 1, -5};
- // int array[] = {-5, -1, -1, 2, -2, -3};
- int array[] = {1, -5, 1, -5};
- calculateLongestAlternating(array);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement