710261. Minimize connections

Medium

Minimize connections

Summary

The problem is to minimize the number of connections needed between a set of houses and a school. The houses are located at different points on a line, and each house can be connected to the school in multiple ways. We need to find the minimum number of connections required such that every house is connected to the school.

Detailed Explanation

The problem can be solved using dynamic programming. Let's break down the solution step by step:

  1. First, we initialize a 2D array dp of size (n+1) x (n+1) where n is the number of houses. The cell dp[i][j] will store the minimum number of connections required to connect house i to the school using the first j points.
  2. We iterate over all houses and for each house, we calculate the minimum number of connections required to connect it to the school. This is done by considering all possible connections from the current house to the school and choosing the one that results in the minimum number of connections.
  3. Finally, we return the value stored in dp[n][n], which represents the minimum number of connections required to connect all houses to the school.

Here's an ASCII art diagram illustrating the concept:

  +---------------+
  |  House 1     |
  +---------------+
           |
           |
           v
  +---------------+
  |  School      |
  +---------------+

  +---------------+
  |  House 2     |
  +---------------+
           |
           |
           v
  +---------------+
  |  School      |
  +---------------+

  ...

Time complexity: O(n^2) Space complexity: O(n^2)

Optimized Solutions

Java

View on GeeksforGeeks
public int minimizeConnections(int[] houses, int n) {
    int[][] dp = new int[n+1][n+1];
    for (int i = 0; i <= n; i++) {
        dp[i][i] = 1;
    }
    for (int i = 1; i <= n; i++) {
        for (int j = 0; j < i; j++) {
            dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j+1]) + 1;
        }
    }
    return dp[n][0];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.