Last Updated: 24 Feb, 2026

Optimal Itinerary for Maximum Profit

Hard

Problem statement

A traveling salesman plans a business trip of exactly k legs (or trips). He starts at his home base, city 0. For any trip from a city i to a city j, there are associated costs and earnings.


You are given three N x N 2D arrays:

Distance[i][j]: The cost of fuel to travel from city i to city j.
Loss[i][j]: An entry fee or tax paid upon arriving at city j from city i.
Gain[i][j]: The revenue earned from business conducted in city j after arriving from city i.


The net profit for a single trip from city i to city j is calculated as Gain[i][j] - Loss[i][j] - Distance[i][j].


Your task is to find the maximum possible total profit the salesman can achieve after completing exactly k trips. The salesman can revisit cities, including his home base.


Return the minimum possible value of x.

Input Format:
The first line contains an integer N, the total number of cities (cities are numbered 0 to N-1).
The second line contains an integer k, the exact number of trips to be made.
The next N lines contain N space-separated integers each, representing the Distance matrix.
The next N lines contain N space-separated integers each, representing the Loss matrix.
The next N lines contain N space-separated integers each, representing the Gain matrix.


Output Format:
The output should be a single long integer representing the maximum possible profit.


Note:
The salesman always starts at city 0 before the first trip.
A trip from city i to city j is a single leg of the journey. A plan with k trips will have a path like c_0 -> c_1 -> ... -> c_k, where c_0 is always city 0.
The total profit is the sum of the net profits of all k individual trips.
If all possible itineraries result in a loss, the answer should be the maximum profit (i.e., the smallest loss, which will be a negative number).