Open In App

Determining Mobile Phone Charging Time Based on Rates

Last Updated : 05 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an initial charge amount C in a mobile phone, it undergoes varying charging rates per minute, as specified within specific ranges ‘Rate’ based on the current charge level. These charging rate ranges are organized in Sorted Order, where each range is defined by three values: a starting point (inclusive), an ending point (non-inclusive), and an associated charging rate (See Example for more clarity). The collective span of all the ranges within the ‘Rate‘ array encompasses values from 0 to 100, covering all intermediary ranges. Your task is to calculate the time required to charge the mobile phone to a specified charge level (T).

Examples:

Input: C = 30, T = 90, Rate = [[0, 30, 4], [30, 60, 10], [60, 90, 5], [90, 100, 10]]
Output: 9
Explanation: Initially mobile charged C = 30 so, to reach 30 to 60 it will charge 10 unit per min which will take 3 min, then to reach 60 to 90 it will charge 5 unit per min which will take 6 min, So in total it will take 3+6=9 min.

Input: C = 70, T = 95, Rate = [[0, 30, 4], [30, 60, 10], [60, 90, 5], [90, 100, 10]]
Output: 4.5
Explanation: Initially mobile charged C = 70 so, to reach 70 to 90 it will charge 5 unit per min which will take 4 min, then to reach 90 to 95 it will charge 10 unit per min which will take 0.5 min, So in total it will take 4+0.5 = 4.5 min .

Approach: To solve the problem follow the below idea:

Iterate through the charging rate ranges (Rates), checking if the current charge level (C) has met the target charge level (T) to exit the loop early. If not, it verifies if C falls within a specific range, computes the needed charge and corresponding time to reach the range’s end using the provided charging rate, and continuously adds up these times to calculate the overall charging duration. Ultimately, it returns the total time required for the entire charging process.

Below is the implementation of the above approach.

C++




// C++ code for the above approach:
#include <iostream>
#include <vector>
 
using namespace std;
 
// Define a function to calculate the time
// required to reach a target charge level.
double chargeNeeded(int C, int T,
                    vector<vector<int> >& Rate)
{
 
    // Initialize the total time spent charging
    double Time = 0;
 
    // Loop through the charging rate ranges.
    for (const vector<int>& range : Rate) {
        int start = range[0];
        int end = range[1];
        int charge_per_minute = range[2];
 
        // Check if the current charge level 'C'
        // has reached the target charge level 'T'.
        if (C == T) {
            break;
        }
 
        // Check if the current charge level 'C'
        // is within the current rate range.
        else if (C < end) {
            // Calculate the amount of charge
            // needed to reach the end of this range.
            int charge_needed = min(end, T) - C;
 
            // Calculate the time required to reach
            // that charge using the current rate.
            double time_required
                = static_cast<double>(charge_needed)
                  / charge_per_minute;
 
            // Add this time to the total time
            // spent charging.
            Time += time_required;
 
            // Update the current charge level
            // 'C' to the end of this range.
            C += charge_needed;
        }
    }
 
    // Return the total time spent charging.
    return Time;
}
 
// Drivers code
int main()
{
    int C = 30;
    int T = 90;
    vector<vector<int> > Rate = { { 0, 30, 4 },
                                  { 30, 60, 10 },
                                  { 60, 90, 5 },
                                  { 90, 100, 10 } };
 
    // Call the function and print the result
    cout << chargeNeeded(C, T, Rate) << endl;
 
    return 0;
}


Java




// Java code for the above approach:
 
import java.util.ArrayList;
import java.util.List;
 
public class ChargingTime {
 
    // Define a function to calculate the time
    // required to reach a target charge level.
    static int chargeNeeded(int C, int T,
                               List<List<Integer>> Rate) {
 
        // Initialize the total time spent charging
        int Time = 0;
 
        // Loop through the charging rate ranges.
        for (List<Integer> range : Rate) {
            int start = range.get(0);
            int end = range.get(1);
            int chargePerMinute = range.get(2);
 
            // Check if the current charge level 'C'
            // has reached the target charge level 'T'.
            if (C == T) {
                break;
            }
 
            // Check if the current charge level 'C'
            // is within the current rate range.
            else if (C < end) {
                // Calculate the amount of charge
                // needed to reach the end of this range.
                int chargeNeeded = Math.min(end, T) - C;
 
                // Calculate the time required to reach
                // that charge using the current rate.
                double timeRequired = (double) chargeNeeded / chargePerMinute;
 
                // Add this time to the total time
                // spent charging.
                Time += timeRequired;
 
                // Update the current charge level
                // 'C' to the end of this range.
                C += chargeNeeded;
            }
        }
 
        // Return the total time spent charging.
        return Time;
    }
 
    // Driver code
    public static void main(String[] args) {
        int C = 30;
        int T = 90;
        List<List<Integer>> Rate = new ArrayList<>();
        Rate.add(List.of(0, 30, 4));
        Rate.add(List.of(30, 60, 10));
        Rate.add(List.of(60, 90, 5));
        Rate.add(List.of(90, 100, 10));
 
        // Call the function and print the result
        System.out.println(chargeNeeded(C, T, Rate));
    }
}
 
// this code is contributed by uttamdp_10


Python3




# Define a function to calculate the time required to reach a target charge level.
def chargeNeeded(C, T, Rate):
    Time = 0  # Initialize the total time spent charging
     
    # Loop through the charging rate ranges.
    for start, end, charge_per_minute in Rate:
        # Check if the current charge level 'C' has reached the target charge level 'T'.
        if C == T:
            break
             
        # Check if the current charge level 'C' is within the current rate range.
        elif C < end:
           
            # Calculate the amount of charge needed to reach the end of this range.
            charge_needed = min(end, T) - C
            # Calculate the time required to reach that charge using the current rate.
            time_required = charge_needed / charge_per_minute
            # Add this time to the total time spent charging.
            Time += time_required
            # Update the current charge level 'C' to the end of this range.
            C += charge_needed
     
    return Time  # Return the total time spent charging.
 
# Driver Code
C = 30
T = 90
Rate = [[0, 30, 4], [30, 60, 10], [60, 90, 5], [90, 100, 10]]
 
# Call the function and print the result
print(chargeNeeded(C, T, Rate))


C#




using System;
using System.Collections.Generic;
 
class GFG
{
    static double ChargeNeeded(int C, int T, List<List<int>> Rate)
    {
        // Initialize the total time spent charging
        double Time = 0;
        // Loop through the charging rate ranges.
        foreach (List<int> range in Rate)
        {
            int start = range[0];
            int end = range[1];
            int chargePerMinute = range[2];
 
            // Check if the current charge level 'C'
            // has reached the target charge level 'T'.
            if (C == T)
            {
                break;
            }
            // Check if the current charge level 'C' is within the current rate range.
            else if (C < end)
            {
                // Calculate the amount of charge
                // needed to reach the end of this range.
                int chargeNeeded = Math.Min(end, T) - C;
                // Calculate the time required to reach
                double timeRequired = (double)chargeNeeded / chargePerMinute;
                Time += timeRequired;
 
                // Update the current charge level
                C += chargeNeeded;
            }
        }
        // Return the total time spent charging.
        return Time;
    }
    // Driver code
    static void Main()
    {
        int C = 30;
        int T = 90;
        List<List<int>> Rate = new List<List<int>>()
        {
            new List<int> {0, 30, 4},
            new List<int> {30, 60, 10},
            new List<int> {60, 90, 5},
            new List<int> {90, 100, 10}
        };
        // Call the function and print the result
        Console.WriteLine(ChargeNeeded(C, T, Rate));
    }
}


Javascript




function GFG(C, T, Rate) {
    let Time = 0; // Initialize the total time spent charging
    // Loop through the charging rate ranges.
    for (let i = 0; i < Rate.length; i++) {
        const [start, end, chargePerMinute] = Rate[i];
        // Check if the current charge level 'C' has reached the
        // target charge level 'T'.
        if (C === T) {
            break;
        }
        // Check if the current charge level 'C' is within
        // the current rate range.
        else if (C < end) {
            // Calculate the amount of charge needed to reach the end of this range.
            const GFG = Math.min(end, T) - C;
            // Calculate the time required to reach that charge using
            // the current rate.
            const timeRequired = GFG / chargePerMinute;
            // Add this time to the total time spent charging.
            Time += timeRequired;
            // Update the current charge level 'C' to
            // the end of this range.
            C += GFG;
        }
    }
    return Time; // Return the total time spent charging.
}
// Driver Code
const C = 30;
const T = 90;
const Rate = [[0, 30, 4], [30, 60, 10], [60, 90, 5], [90, 100, 10]];
// Call the function and print the result
console.log(GFG(C, T, Rate));


Output

9




Time Complexity: O(N), where n is the number of different Rates.
Auxiliary Space: O(1).



Similar Reads

Determining topology formed in a Graph
Given a graph containing n edges. The task is to find the topology formed by the given set of edges in that graph. Examples: Input: edges = [(1, 2), (2, 3), (3, 1)]Output: "linear"Explanation: This test case contains three edges that are connected end-to-end, forming a linear topology. Input: edges = [(1, 2), (1, 3), (1, 4), (1, 5)]Output: "star"Ex
9 min read
Determining Sandwich type for Palindromic Matrix
Given a 2D matrix, print if it is a Horizontal, Vertical, Proper, or Improper Sandwich. If all rows of the matrix are palindrome, then it can be folded in a vertical sense so it is a Vertical Sandwich Similarly, if all columns are palindrome, then they can be folded in a horizontal sense so it is a Horizontal Sandwich If any one or none of the rows
9 min read
Determining Word Equivalence between Arrays
Given two arrays A[] and B[] of strings and an array of pairs[] where each pair of words is equivalent and also follows transitive property (i.e. if x=y and y=z then x=z), determine whether each ith word of string A is equivalent to ith word of string B. Examples: Input: A = ["blue", "sky", "is"], B = ["pink", "sky", "of"], pairs = [["blue", "hi"],
8 min read
Determining the inconsistently weighted object
Given N objects numbered from 1 to N out of which all are of the same weights except only one object which is not known beforehand. We are also given Q comparisons, in each of which an equal number of objects are placed on both sides of a balance scale, and we are told the heavier side. The task is to find the inconsistently weighted object or dete
10 min read
Time difference between expected time and given time
Given the initial clock time h1:m1 and the present clock time h2:m2, denoting hour and minutes in 24-hours clock format. The present clock time h2:m2 may or may not be correct. Also given a variable K which denotes the number of hours passed. The task is to calculate the delay in seconds i.e. time difference between expected time and given time. Ex
5 min read
Array-Based Queues vs List-Based Queues
Queues:A queue is a linear data structure in which elements are inserted from one end called the rear end and deleted from another end called the front end. It follows FIFO (First In First Out) technique.Insertion in the queue is called enqueue and deletion in the queue is called dequeue.Queues can be implemented in two ways: Array-based queues and
3 min read
Java ArrayList to print all possible words from phone digits
Given a keypad of a mobile, and keys that need to be pressed, the task is to print all the words which are possible to generate by pressing these numbers. Examples: Input: str = "12" Output: [ad, bd, cd, ae, be, ce, af, bf, cf] Explanation: The characters that can be formed by pressing 1 is a, b, c and by pressing 2 characters d, e, f can be formed
4 min read
Find the last two missing digits of the given phone number
Given eight digits of a phone number as an integer N, the task is to find the missing last two digits and print the complete number when the last two digits are the sum of given eight digits.Examples: Input: N = 98765432 Output: 9876543244Input: N = 10000000 Output: 1000000001 Approach: Get the eight digits of the phone number from N one by one usi
5 min read
Menu-Driven program for Phone Directory
Problem Statement: Write a menu-driven program for using switch-case with following features: Store Contact numbers of peopleSearch for the Contact numbers using their namesSearch for the Contact numbers using their numberDelete a Contact numberUpdate a Contact number Examples: Approach: The idea is to use switch case for switching the case for men
9 min read
Convert textual Phone Number to 10 digit numerical number
Given a string S of size N containing lowercase English letters, representing a phone number(all phone numbers will be 10 digits) in words, the task is to convert the number into digits. Repeating digits can be shortened as follows: If any digit repeats two times then in words is written as "double".If any digit repeats three times then in words is
9 min read
Practice Tags :