WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Dynamic Programming · Guru · question 84 of 100

Implement the solution to the Maximum Weight Independent Set in a Path Graph with Non-Negative Weights problem using dynamic programming.?

📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

The Maximum Weight Independent Set in a Path Graph problem is defined as follows: given a path graph G = (V, E) with non-negative weights w1, w2, ..., wn on its n vertices, find a set S of non-adjacent vertices such that the sum of their weights is maximum.

The dynamic programming approach to this problem involves computing the maximum weight independent set up to each vertex i in the graph. By doing so, we can derive the maximum weight independent set of the entire graph by considering the two cases: either vertex n is in the set or it is not.

Let MISi be the maximum weight independent set up to vertex i. We can compute MISi using the following recurrence:

MISi = max(MISi-1, MISi-2 + wi)

where MISi-1 represents the maximum weight independent set that excludes vertex i, and MISi-2 + wi represents the maximum weight independent set that includes vertex i.

To compute the maximum weight independent set of the entire graph, we simply consider the two cases:

1. If vertex n is in the set, then the maximum weight independent set is MISn.

2. If vertex n is not in the set, then the maximum weight independent set is MISn-1.

Therefore, the solution to the problem is max(MISn, MISn-1).

Here is the Java code that implements this dynamic programming approach:

public static int maxWeightIndependentSet(int[] weights) {
    int n = weights.length;
    int[] mis = new int[n];
    mis[0] = weights[0];
    mis[1] = Math.max(weights[0], weights[1]);

    for (int i = 2; i < n; i++) {
        mis[i] = Math.max(mis[i-1], mis[i-2] + weights[i]);
    }

    return mis[n-1];
}

In this code, ‘weights‘ is an array of non-negative weights on the vertices of the path graph. The ‘mis‘ array stores the maximum weight independent set up to each vertex i in the graph. The ‘maxWeightIndependentSet‘ function returns the maximum weight independent set of the entire graph by computing the maximum of MISn and MISn-1. The time complexity of this algorithm is O(n), where n is the number of vertices in the path graph.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Dynamic Programming interview — then scores it.
📞 Practice Dynamic Programming — free 15 min
📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

All 100 Dynamic Programming questions · All topics