Final code. Verified on small input. Large input is probably failing because of the long long overflow..