You are given an array where element i is a price on day i.
Choose one day to buy and a later day to sell. Return the largest profit you can make, or 0 if no profit is possible.
maxProfit({7, 1, 5, 3, 6, 4})
The wrong ones are this same code with between two and five lines changed. Some of those changes do not compile. There is no Run button: running all three would turn this into a vote rather than a reading.
| 1 | int maxProfit(const vector<int>& prices) { |
| 2 | |
| 3 | int cheapest = INT_MAX; |
| 4 | int ans = 0; |
| 5 | |
| 6 | for (int x : prices) { |
| 7 | |
| 8 | if (x < cheapest) { |
| 9 | cheapest = x; |
| 10 | } |
| 11 | |
| 12 | int gap = x - cheapest; |
| 13 | |
| 14 | if (gap > ans) { |
| 15 | ans = gap; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | return ans; |
| 20 | } |
| 1 | int maxProfit(const vector<int>& prices) { |
| 2 | |
| 3 | int cheapest = INT_MIN; |
| 4 | int ans = 0; |
| 5 | |
| 6 | for (int x : prices) { |
| 7 | |
| 8 | if (!(x < cheapest)) { |
| 9 | cheapest = x; |
| 10 | } |
| 11 | |
| 12 | int gap = x - cheapest; |
| 13 | |
| 14 | if (gap > ans) { |
| 15 | ans = gap; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | return ans; |
| 20 | } |
| 1 | int maxProfit(const vector<int>& prices) { |
| 2 | |
| 3 | int cheapest = INT_MIN; |
| 4 | int ans = 0; |
| 5 | |
| 6 | for (int x : prices) { |
| 7 | |
| 8 | if (!(x < cheapest)) { |
| 9 | cheapest = x; |
| 10 | } |
| 11 | |
| 12 | int gap = x - cheapest; |
| 13 | |
| 14 | if (!(gap > ans)) { |
| 15 | ans = gap; |
| 16 | } |
| 17 | } |
| 18 | |
| 19 | return ans; |
| 20 | } |