My jave accepted solution with O(N) time and O(1) space
The idea is to find so far min price.\n\n     public int maxProfit(int[] prices) {\n    \t\t if (prices.length == 0) {\n    \t\t\t return 0 ;\n    \t\t }\t\t\n 
The idea is to find so far min price.\n\n     public int maxProfit(int[] prices) {\n    \t\t if (prices.length == 0) {\n    \t\t\t return 0 ;\n    \t\t }\t\t\n    \t\t int max = 0 ;\n    \t\t int sofarMin = prices[0] ;\n    \t     for (int i = 0 ; i < prices.length ; ++i) {\n    \t    \t if (prices[i] > sofarMin) {\n    \t    \t\t max = Math.max(max, prices[i] - sofarMin) ;\n    \t    \t } else{\n    \t    \t\tsofarMin = prices[i];  \n    \t    \t }\n    \t     }\t     \n    \t    return  max ;\n    \t }
[]