#3543

Maximum Weighted K-Edge Path

Medium
Hash TableDynamic ProgrammingGraph TheoryHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * k)
Space
O(1)
O(n * k)
💡

Intuition

Time O(n * k)Space O(n * k)

Utilize dynamic programming to keep track of the maximum weight sums for paths of different lengths ending at each node, updating iteratively.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table where dp[i][j] represents the maximum weight sum using exactly i edges ending at node j.
  2. 2Step 2: Initialize dp[0][node] = 0 for all nodes and iterate through edges to update the DP table.
  3. 3Step 3: After processing, find the maximum value in dp[k][j] that is less than t.
solution.py7 lines
1def maxWeightedKEdgePath(n, edges, k, t):
2    dp = [[-1] * n for _ in range(k + 1)]
3    for u, v, w in edges:
4        for i in range(k, 0, -1):
5            if dp[i - 1][u] != -1:
6                dp[i][v] = max(dp[i][v], dp[i - 1][u] + w)
7    return max((dp[k][j] for j in range(n) if dp[k][j] < t), default=-1)

Complexity note: This complexity arises from iterating through edges and updating the DP table for k edges, leading to a linear relationship with respect to edges and path length.

  • 1Dynamic programming can efficiently track multiple states.
  • 2DAG properties allow for topological sorting and optimized pathfinding.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.