The perfect place for easy learning...

Java Programming Language

×

List of Programs


Java Practical Programs


Aim


Given an array of numbers, you are expected to return the sum of the longest sequence of even numbers in the array. If there are no even numbers in the array, you are expected to return -1. The array will contain numbers >= 0.
If there are more than one group of elements in the array having the longest sequence of even numbers, you are expected to return the total sum of all those even numbers.

Implementation


Java Program for sum of longest sequence of even numbers in an array.
import java.util.*;

public class SumOfEvenSeq {
    
    public static void main(String[] args) {
            
        int array[] = {13, 15, 12, 18, 18, 14, 5, 12, 13, 32, 34, 5, 66, 78, 78, 79};
    
        List counts = new ArrayList();
        List sums = new ArrayList();
    
        int count = 0, sum = 0, result = 0;
            
        for(int i = 0; i < array.length; i++) {
            if(array[i]%2 == 0) {
                sum = sum + array[i];
                count++;
                if(i == (array.length-1)) {
                    counts.add(count);
                    sums.add(sum);
                }
            }
            else {
                counts.add(count);
                sums.add(sum);
                count = sum = 0;
            }
        }
            
        int longest = Collections.max(counts);
        
        for(int i = 0; i < counts.size(); i++) {
            if(counts.get(i) == longest) {
                result = result + sums.get(i);
            }
        }
    
        System.out.println(result);
    }
    
}

Result



   Download Source Code

Place your ad here
Place your ad here