optimized greedy and also added test cases