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

Complexity:

time complexity is O(N)

space complexity is O(1)

Execution:

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

Solution:

#!/usr/bin/py
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


 #include<iostream>
 #include<vector>
 #include<math.h>
 #include<array>
 using namespace std;
 int main()
 {
    long n,m;
    long answer=0,t;
    cin>>n>>m;
    t = m;
    while(t--){
        long a,b,k;
        cin>>a>>b>>k;
        answer = answer + (abs(a-b)+1)*k;
    }
    answer = floor(answer/n);
    cout<<answer<<endl;
    return 0;
 }

Twitter, Facebook

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.