HackerRank 'Filling Jars' Solution

Martin Kysel · March 3, 2015

Short Problem Definition:

Animesh has N empty candy jars, numbered from 1 to N, with infinite capacity. He performs M operations. Each operation is described by 3 integers a, b and k. Here, a and b are indices of the jars, and k is the number of candies to be added inside each jar whose index lies between_a_ and b (both inclusive). Can you tell the average number of candies after M operations?

Filling Jars


time complexity is O(N)

space complexity is O(1)


Keep a sum variable. Compute the average at the end.


if __name__ == '__main__':
    n,m = map(int, raw_input().split())

    answer = 0

    for _ in xrange(m):
        a, b, k = map(int, raw_input().split())
        answer += (abs(a-b)+1)*k
    print answer//n

 using namespace std;
 int main()
    long n,m;
    long answer=0,t;
    t = m;
        long a,b,k;
        answer = answer + (abs(a-b)+1)*k;
    answer = floor(answer/n);
    return 0;

Twitter, Facebook