1:题目信息

题目链接

2:解题思路

3:Java代码

  1. public int maxProfit(int[] prices) {
  2. if (prices.length <= 1) {
  3. return 0;
  4. }
  5. int max = 0;
  6. for (int x = 0; x < prices.length; x++) {
  7. for (int y = x + 1; y < prices.length; y++) {
  8. int temp = prices[x] - prices[y];
  9. if (temp < 0) {
  10. if (Math.abs(temp) >= max) {
  11. max = Math.abs(temp);
  12. }
  13. }
  14. }
  15. }
  16. return max;
  17. }
  18. public static int maxProfit2(int[] prices) {
  19. if (prices.length <= 1) {
  20. return 0;
  21. }
  22. int min = prices[0], max = 0;
  23. for (int i = 1; i < prices.length; i++) {
  24. max = Math.max(max, prices[i] - min);
  25. min = Math.min(min, prices[i]);
  26. }
  27. return max;
  28. }

4:Go代码