Codility - TieRopes  

by ne on 2022-08-27 under Algo/DS/Problems tagged with codility

The problem belongs to Codility, here is the link to the problem

Following code segment contains the description in the class comments, followed by fully working solution

 

 



/**
 * There are N ropes numbered from 0 to N − 1, whose lengths are given in an array A, lying on the floor in a line. For each I (0 ≤ I < N), the length of rope I on the line is A[I].
 *
 * We say that two ropes I and I + 1 are adjacent. Two adjacent ropes can be tied together with a knot, and the length of the tied rope is the sum of lengths of both ropes. The resulting new rope can then be tied again.
 *
 * For a given integer K, the goal is to tie the ropes in such a way that the number of ropes whose length is greater than or equal to K is maximal.
 *
 * For example, consider K = 4 and array A such that:
 *
 *     A[0] = 1
 *     A[1] = 2
 *     A[2] = 3
 *     A[3] = 4
 *     A[4] = 1
 *     A[5] = 1
 *     A[6] = 3
 * The ropes are shown in the figure below.
 *
 *
 *
 * We can tie:
 *
 * rope 1 with rope 2 to produce a rope of length A[1] + A[2] = 5;
 * rope 4 with rope 5 with rope 6 to produce a rope of length A[4] + A[5] + A[6] = 5.
 * After that, there will be three ropes whose lengths are greater than or equal to K = 4. It is not possible to produce four such ropes.
 */
public class TieRopes {
    public int solution(int K, int[] A) {

        int max=0;
        int ls=A[0];
        if(ls>=K){
            max++;
            ls=0;
        }
        for(int i=1;i=K){
                max++;
                ls=0;
            }else{
                ls+=A[i];
            }
        }
        return max;
    }
    public static void main(String[] args){
        System.out.println(new TieRopes().solution(4, new int[]{1,2,3,4,1,1,3}));
        System.out.println(new TieRopes().solution(1, new int[]{1}));
    }
}