Algorithm


Problem Name: Data Structures - Truck Tour

Problem Link: https://www.hackerrank.com/challenges/truck-tour/problem?isFullScreen=true

In this HackerRank in Data Structures - Truck Tour solutions

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N - 1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump.

Initially, you have a tank of infinite capacity carrying no petrol. You can start the tour at any of the petrol pumps. Calculate the first point from where the truck will be able to complete the circle. Consider that the truck will stop at each of the petrol pumps. The truck will move one kilometer for each litre of the petrol.

Input Format

The first line will contain the value of N .

The next N lines will contain a pair of integers each, i.e. the amount of petrol that petrol pump will give and the distance between that petrol pump and the next petrol pump.

Constraints:

1 <= n <= 10**5

1 <= amount of petrol, distance <= 10**9

Output Format

An integer which will be the smallest index of the petrol pump from which we can start the tour.

Sample Input

3
1 5
10 3
3 4

Sample Output

1

Explanation

We can start the tour from the second petrol pump.

Input Format

The first line will contain the value of N.

 

The next N lines will contain a pair of integers each, i.e. the amount of petrol that petrol pump will give and the distance between that petrol pump and the next petrol pump.
Constraints:
1 <= n <= 10**5
q <= amount of petrol distance <=  9

Output Format

An integer which will be the smallest index of the petrol pump from which we can start the tour.

Sample Input

3
1 5
10 3
3 4

Sample Output

1

Explanation

We can start the tour from the second petrol pump.

 

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming


#include <bits/stdc++.h>
#inclu<vector>
#include <queue>

using namespace std;

/*************************************EDITABLE PART*********************/
int truckTour(vector < vector<int>> petrolpumps) {
    int n = petrolpumps.size();
    int petrolRemain = 0;
    int state = 0;
    
    for (int i=0; i < n; i++){
        int petrol = petrolpumps[i][0];     // get petrol value from matrix
        int distance = petrolpumps[i][1];   // get distance value from matrix
        petrolRemain += petrol - distance;
        
        // check if remaining petrol is empty, reset the counter, and start from the next pumpstation
        if (petrolRemain  <  0){
            state = i+1;
            petrolRemain = 0;
        }
    }
return state;
}
/***********************************************************************/

int main()
{
    ofstream fout(getenv("OUTPUT_PATH"));

    int n;
    cin >> n;
    cin.ignore(numeric_limits < streamsize>::max(), '\n');

    vector<vector<int>> petrolpumps(n);
    for (int petrolpumps_row_itr = 0; petrolpumps_row_itr  <  n; petrolpumps_row_itr++) {
        petrolpumps[petrolpumps_row_itr].resize(2);

        for (int petrolpumps_column_itr = 0; petrolpumps_column_itr  <  2; petrolpumps_column_itr++) {
            cin >> petrolpumps[petrolpumps_row_itr][petrolpumps_column_itr];
        }

        cin.ignore(numeric_limits < streamsize>::max(), '\n');
    }

    int result = truckTour(petrolpumps);

    fout << result << "\n";

    fout.close();

    return 0;
}
Copy The Code & Try With Live Editor

#3 Code Example with Python Programming

Code - Python Programming


def truckTour(petrolpumps):
    # starting from pump 0, if at some point the fuel goes below zero, then non of the pumps
    # we met in this trip can serve as a starting pump to complete the whole lap. This is
    # straightforward because a complete lap requires more or equal amount of fuels than this
    # trip.
    n = len(petrolpumps)
    rem = [x[0] - x[1] for x in petrolpumps]
    rem += rem # create a 2nd lap
    balance = 0
    out = 0
    for i in range(n):
        balance += rem[i]
        if balance < 0:
            out = i + 1
            balance = 0
    return out
Copy The Code & Try With Live Editor

#4 Code Example with Javascript Programming

Code - Javascript Programming


'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the 'truckTour' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts 2D_INTEGER_ARRAY petrolpumps as parameter.
 */

function truckTour(petrolpumps) {
    let petrol = 0, distance = 0, first = 0;
    for (let i=0; i < petrolpumps.length; i++){
        petrol+=petrolpumps[i][0];
        distance+=petrolpumps[i][1];
        if (petrol < distance){
            petrol=0, distance=0;
            first=i+1;
        }
    } 
    return first;
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const n = parseInt(readLine().trim(), 10);

    let petrolpumps = Array(n);

    for (let i = 0; i  <  n; i++) {
        petrolpumps[i] = readLine().replace(/\s+$/g, '').split(' ').map(petrolpumpsTemp => parseInt(petrolpumpsTemp, 10));
    }

    const result = truckTour(petrolpumps);

    ws.write(result + '\n');

    ws.end();
}
Copy The Code & Try With Live Editor

#4 Code Example with Java Programming

Code - Java Programming


import java.util.Scanner;

public class Solution {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		int sum = 0;
		int startIndex = 0;
		int N = in.nextInt();
		for (int i = 0; i  <  N; i++) {
			int petrol = in.nextInt();
			int distance = in.nextInt();
			sum += petrol - distance;

			if (sum  <  0) {
				sum = 0;
				startIndex = i + 1;
			}
		}
		System.out.println(startIndex);

		in.close();
	}
}
Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Minimum Average Waiting Time solution in Hackerrank - Hacerrank solution C, C++, java,js, Python
Next
[Solved] Array and simple queries solution in Hackerrank - Hacerrank solution C, C++, java,js, Python