linear time solution for maxProfit