The Wayback Machine - https://web.archive.org/web/20240629013108/https://www.geeksforgeeks.org/number-days-tank-will-become-empty/
Open In App

Number of days after which tank will become empty

Last Updated : 31 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a tank with capacity C liters which is completely filled in starting. Everyday tank is filled with l liters of water and in the case of overflow extra water is thrown out. Now on i-th day i liters of water is taken out for drinking. We need to find out the day at which tank will become empty the first time.

Examples:  

Input : Capacity = 5        
        l = 2
Output : 4
At the start of 1st day, water in tank = 5    
and at the end of the 1st day = (5 - 1) = 4
At the start of 2nd day, water in tank = 4 + 2 = 6
but tank capacity is 5 so water = 5
and at the end of the 2nd day = (5 - 2) = 3
At the start of 3rd day, water in tank = 3 + 2 = 5
and at the end of the 3rd day = (5 - 3) = 2
At the start of 4th day, water in tank = 2 + 2 = 4
and at the end of the 4th day = (4 - 4) = 0
    So final answer will be 4
Recommended Practice

We can see that tank will be full for starting (l + 1) days because water taken out is less than water being filled. After that, each day water in the tank will be decreased by 1 more liter and on (l + 1 + i)th day (C – (i)(i + 1) / 2) liter water will remain before taking drinking water. 

Now we need to find a minimal day (l + 1 + K), in which even after filling the tank by l liters we have water less than l in tank i.e. on (l + 1 + K – 1)th day tank becomes empty so our goal is to find minimum K such that, 
C – K(K + 1) / 2 <= l

We can solve above equation using binary search and then (l + K) will be our answer. Total time complexity of solution will be O(log C) 

C++


                    

Java

// Java code to find number of days after which
// tank will become empty
public class Tank_Empty {
     
    // Utility method to get sum of first n numbers
    static int getCumulateSum(int n)
    {
        return (n * (n + 1)) / 2;
    }
      
    // Method returns minimum number of days after
    // which tank will become empty
    static int minDaysToEmpty(int C, int l)
    {
        // if water filling is more than capacity then
        // after C days only tank will become empty
        if (C <= l)
            return C;   
      
        // initialize binary search variable
        int lo = 0;
        int hi = (int)1e4;
        int mid;
      
        // loop until low is less than high
        while (lo < hi) {
             
            mid = (lo + hi) / 2;
      
            // if cumulate sum is greater than (C - l)
            // then search on left side
            if (getCumulateSum(mid) >= (C - l))
                hi = mid;
              
            // if (C - l) is more then search on
            // right side
            else
                lo = mid + 1;       
        }
      
        // final answer will be obtained by adding
        // l to binary search result
        return (l + lo);
    }
      
    // Driver code to test above methods
    public static void main(String args[])
    {
        int C = 5;
        int l = 2;
      
        System.out.println(minDaysToEmpty(C, l));
    }
}
// This code is contributed by Sumit Ghosh

                    

Python3


                    

C#

// C# code to find number
// of days after which
// tank will become empty
using System;
 
class GFG
{
     
    // Utility method to get
    // sum of first n numbers
    static int getCumulateSum(int n)
    {
        return (n * (n + 1)) / 2;
    }
     
    // Method returns minimum
    // number of days after
    // which tank will become empty
    static int minDaysToEmpty(int C,
                              int l)
    {
        // if water filling is more
        // than capacity then after
        // C days only tank will
        // become empty
        if (C <= l)
            return C;
     
        // initialize binary
        // search variable
        int lo = 0;
        int hi = (int)1e4;
        int mid;
     
        // loop until low is
        // less than high
        while (lo < hi)
        {
             
            mid = (lo + hi) / 2;
     
            // if cumulate sum is
            // greater than (C - l)
            // then search on left side
            if (getCumulateSum(mid) >= (C - l))
                hi = mid;
             
            // if (C - l) is more then
            // search on right side
            else
                lo = mid + 1;
        }
     
        // final answer will be
        // obtained by adding
        // l to binary search result
        return (l + lo);
    }
     
    // Driver code
    static public void Main ()
    {
        int C = 5;
        int l = 2;
 
        Console.WriteLine(minDaysToEmpty(C, l));
    }
}
 
// This code is contributed by ajit

                    

Javascript


                    

Output: 

4


Alternate Solution : 
It can be solved mathematically with a simple formula:

Let’s Assume C>L. Let d be the amount of days after the Lth when the tank become empty.During that time, there will be (d-1)refills and d withdrawals. 
Hence we need to solve this equation : 
C+(d-1)*L=\sum_{i=1}^{d} Withdrawal_i
Sum of all withdrawals is a sum of arithmetic progression,therefore : 
C+(d-1)*L=\frac {L+1+L+d}{2}*2
2C +2dL - 2L=2dL+d +d^2
d^2+d-2(C-L)=0

Discriminant = 1+8(C-L)>0,because C>L. 
Skipping the negative root, we get the following formula: 
d=-1 +\frac { \sqrt{1-8(C-L)} }{2}
Therefore, the final answer is: 
min,days=L +ceil\left ( \frac { \sqrt{1-8(C-L)}-1 }{2}\right )
 

C++


                    

Java

// Java code to find number of days
// after which tank will become empty
import java.lang.*;
class GFG {
     
// Method returns minimum number of days
// after which tank will become empty
static int minDaysToEmpty(int C, int l)
{
    if (l >= C) return C;
     
    double eq_root = (Math.sqrt(1 + 8 *
                     (C - l)) - 1) / 2;
    return (int)(Math.ceil(eq_root) + l);
}
 
// Driver code
public static void main(String[] args)
{
    System.out.println(minDaysToEmpty(5, 2));
    System.out.println(minDaysToEmpty(6514683, 4965));
}
}
 
// This code is contributed by Smitha Dinesh Semwal.

                    

Python3

# Python3 code to find number of days
# after which tank will become empty
import math
 
# Method returns minimum number of days 
# after which tank will become empty
def minDaysToEmpty(C, l):
 
    if (l >= C): return C
     
    eq_root = (math.sqrt(1 + 8 * (C - l)) - 1) / 2
    return math.ceil(eq_root) + l
 
# Driver code
print(minDaysToEmpty(5, 2))
print(minDaysToEmpty(6514683, 4965))
 
# This code is contributed by Smitha Dinesh Semwal.

                    

C#

// C# code to find number
// of days after which
// tank will become empty
using System;
 
class GFG
{
     
// Method returns minimum
// number of days after
// which tank will become empty
static int minDaysToEmpty(int C,
                          int l)
{
    if (l >= C) return C;
     
    double eq_root = (Math.Sqrt(1 + 8 *
                     (C - l)) - 1) / 2;
    return (int)(Math.Ceiling(eq_root) + l);
}
 
// Driver code
static public void Main ()
{
    Console.WriteLine(minDaysToEmpty(5, 2));
    Console.WriteLine(minDaysToEmpty(6514683,
                                     4965));
}
}
 
// This code is contributed by ajit

                    

PHP

<?php
// PHP code to find number
// of days after which
// tank will become empty
 
// Method returns minimum
// number of days after
// which tank will become empty
function minDaysToEmpty($C, $l)
{
    if ($l >= $C)
        return $C;
     
    $eq_root = (int)sqrt(1 + 8 *
                   ($C - $l) - 1) / 2;
    return ceil($eq_root) + $l;
}
 
// Driver code
echo minDaysToEmpty(5, 2), "\n";
echo minDaysToEmpty(6514683,
                    4965), "\n";
 
// This code is contributed
// by akt_mit
?>

                    

Javascript

<script>
 
// Javascript code to find number
// of days after which
// tank will become empty
 
// Method returns minimum
// number of days after
// which tank will become empty
function minDaysToEmpty(C, l)
{
    if (l >= C) return C;
 
    let eq_root = (Math.sqrt(1 + 8 *
                            (C - l)) - 1) / 2;
    return (Math.ceil(eq_root) + l);
}
 
// Driver code
document.write(minDaysToEmpty(5, 2) + "</br>");
document.write(minDaysToEmpty(6514683, 4965));
 
// This code is contributed by suresh07
 
</script>

                    

Output : 

4
8573


Thanks to Andrey Khayrutdinov for suggesting this solution.


 



Similar Reads

Program to check if water tank overflows when n solid balls are dipped in the water tank
Given the dimensions of cylindrical water tank, spherical solid balls and the amount of water present in the tank check if water tank will overflow when balls are dipped in the water tank. Examples : input : H = 10, r = 5 h = 5 N = 2, R = 2 output : Not in overflow state Explanation : water tank capacity = 3.14 * r * r * H = 3.14 * 5 * 5 * 10 = 785
8 min read
Find amount of water wasted after filling the tank
Given the volume V of a tank in liter. There is a pump which is filling the tank at speed of M liter per minute. There is a leakage at the bottom of the tank which wasting water at speed N liter per minute. Given N is less than M. The task is to calculate how much amount of water will be wasted if leakage is seen after filling the full tank.Example
5 min read
Program to check if tank will overflow, underflow or filled in given time
Given a tank with definite height and radius and the flow of water available to fill the tank. Determine whether the tank will overflow or not in a given amount of time. Note: The flow of water will be available in volume per minute.Examples: --r=5-- ---------- ^ | | | | | | | | h = 10 | | | ---------- ^ rate_of_flow = 10 Input : given_time = 10.0
6 min read
Number of days until all chocolates become unhealthy
Pablo has a square chocolate Box of size n x n in which a variety of healthy chocolates are present denoted by 'H' initially but he finds out that some of the chocolates are rotten and unhealthy denoted by 'U'. In one day the rotten chocolates make all its neighboring chocolates unhealthy. This goes on and on until all chocolates present in the cho
15+ min read
Largest number not greater than N which can become prime after rearranging its digits
Given a number N, the task is to find the largest number less than or equal to the given number N such that on rearranging its digits it can become prime.Examples: Input : N = 99 Output : 98 Explanation : We can rearrange the digits of 98 to 89 and 89 is a prime number. Input : N = 84896 Output : 84896 Explanation : We can rearrange the digits of 8
11 min read
String slicing in Python to check if a string can become empty by recursive deletion
Given a string “str” and another string “sub_str”. We are allowed to delete “sub_str” from “str” any number of times. It is also given that the “sub_str” appears only once at a time. The task is to find if “str” can become empty by removing “sub_str” again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
2 min read
Check if a string can become empty by recursively deleting a given sub-string
Given a string "str" and another string "sub_str". We are allowed to delete "sub_str" from "str" any number of times. It is also given that the "sub_str" appears only once at a time. The task is to find if "str" can become empty by removing "sub_str" again and again. Examples: Input : str = "GEEGEEKSKS", sub_str = "GEEKS" Output : Yes Explanation :
8 min read
Total number of cells covered in a matrix after D days
Given an N * M matrix and a starting position (X, Y) of a virus, the task is to find out the number of covered cells after D days, if the virus spreads from its current cell to its adjacent cells every day. Examples: Input: N = 5, M = 5, X = 1, Y = 3, D = 3 Output: 15 Explanation: We can clearly see from the picture that 15 cells are covered after
8 min read
Date after adding given number of days to the given date
Given a date and a positive integer x. The task is to find the date after adding x days to the given date Examples: Input : d1 = 14, m1 = 5, y1 = 2017, x = 10Output : d2 = 24, m2 = 5, y2 = 2017 Input : d1 = 14, m1 = 3, y1 = 2015, x = 366Output : d2 = 14, m2 = 3, y2 = 2016 Method 1: 1) Let given date be d1, m1 and y1. Find offset (number of days spe
12 min read
Maximize number of days for which P chocolates can be distributed consecutively to N people
Given an integer, P denoting the number of chocolates and an array a[] where ai denotes the type of ith chocolate. There are N people who want to eat chocolate every day. Find the maximum number of consecutive days for which N people can eat chocolates considering the following conditions: Each of the N people must eat exactly one chocolate on a pa
9 min read
three90RightbarBannerImg