Program solves most testCases but gets stackoverflow for others. Needs debugging
Added an iterative algorithm that correctly solves all test cases