Last Updated: 30 Mar, 2026

Maximum Value Path in a Graph

Moderate

Problem statement

You are given a directed graph with N nodes (numbered 0 to N-1), where each node has an integer value. You are also given an integer k.


You can start your journey at any node in the graph. From your current node, you can move to any of its neighbors by following a directed edge. Each move takes one step. You are allowed to perform at most k moves.


Each time you visit a node (including your starting node), you collect its value. You are allowed to visit the same node multiple times, and its value is added to your total each time you visit.


Your task is to find the maximum possible total value you can accumulate after a path of at most k moves.


Input Format:
The first line contains three space-separated integers: N (number of nodes), M (number of directed edges), and k (maximum number of moves).

The second line contains N space-separated integers, representing the values of nodes 0 to N-1.

The next M lines each contain two space-separated integers u and v, representing a directed edge from node u to node v.


Output Format:
Your function should return a single long integer representing the maximum possible total value. The runner code will handle printing.


Notes:
This problem can be solved efficiently using dynamic programming. Let dp[i][j] be the maximum value of a path of exactly i moves ending at node j. The state transition would be:

dp[i][j] = value[j] + max(dp[i-1][p]) for all nodes p that have an edge leading to j.

The base case is dp[0][j] = value[j] for all j. The final answer will be the maximum value found anywhere in the dp table.