Connect Multiple Ropes With Minimum Cost

package org.wesome.dsalgo;

import java.util.PriorityQueue;

public class MinCostRope {
    static int minCostRope(int arr[]) {
        int size = arr.length;
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int i = 0; i < size; i++) {
            pq.add(arr[i]);
        }
        int result = 0;
        while (pq.size() > 1) {
            int ropeOne = pq.poll();
            int roteTwo = pq.poll();
            int combine = ropeOne + roteTwo;
            result = result + (combine);
            pq.add(combine);
        }
        return result;
    }
}
package org.wesome.dsalgo;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import static org.wesome.dsalgo.MinCostRope.minCostRope;

public class MinCostRopeTest {
    @Test
    void minCostRopeTest1() {
        int arr[] = {4, 3, 2, 6};
        Assertions.assertEquals(29, minCostRope(arr));
    }
}
plugins {
    id 'java'
    id "io.freefair.lombok" version "6.2.0"
}

group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom annotationProcessor
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}

test {
    useJUnitPlatform()
}

 

follow us on