MaxNonoverlappingSegments

Find a maximal set of non-overlapping segments.


Solution:

Solution to Codility's Max Non Overlapping Segments problem which is from the Codility Lesson 16: Greedy algorithms and, is solved in Java 8 with 100% performance and correctness scores. The goal here is to find a maximal set of non-overlapping segments. You can find the question of this MaxNonoverlappingSegments problem in the Codility website.


package Codility.Lesson16;

import java.util.*;

public class MaxNonoverlappingSegments {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a1 = { 1, 3, 7, 9, 9 };
		int[] a2 = { 5, 6, 8, 9, 10 };
		int result = solution(a1, a2);
		System.out.println(result);
	}

	public static int solution(int[] A, int[] B) {
		int N = A.length;
		if (N <= 1) {
			return N;
		}

		int cnt = 1;
		int prev_end = B[0];

		int curr;
		for (curr = 1; curr < N; curr++) {
			if (A[curr] > prev_end) {
				cnt++;
				prev_end = B[curr];
			}
		}

		return cnt;
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *