TieRopes

Tie adjacent ropes to achieve the maximum number of ropes of length >= K.


Solution:

Solution to Codility's Tie Ropes 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 tie adjacent ropes to achieve the maximum number of ropes of length >= k. You can find the question of this TieRopes problem in the Codility website.


package Codility.Lesson16;

import java.util.*;

public class TieRopes {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a1 = { 1, 2, 3, 4, 1, 1, 3 };
		int k = 4;
		int result = solution(k, a1);
		System.out.println(result);
	}

	public static int solution(int K, int[] A) {
		int N = A.length;
		int cnt = 0;
		int sum = 0;

		for (int i = 0; i < N; i++) {
			sum += A[i];
			if (sum >= K) {
				cnt++;
				sum = 0;
			}
		}
		return cnt;
	}
}

Leave a Reply

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