一:解题思路
这个题目有2种解法。第一种为暴力破解法,求出所有可能的情况,然后得到最大值。Time:O(n^2)。Space:O(1)
第二种方法,采用动态规划的思想。Time:O(n),Space:O(1)
二:完整代码示例 (C++版和Java版)
第一种方法C++:
class Solution { public: int max(int a, int b) { return a > b ? a : b; } int maxProfit(vector<int>& prices) { int maxPrice = 0; if (prices.size() < 2) return 0; for (int i = 0; i < prices.size(); i++) { for (int j = i + 1; j < prices.size(); j++) { maxPrice = max(maxPrice, (prices[j] - prices[i])); } } return maxPrice; } };
第一种方法Java:
class Solution { public int maxProfit(int[] prices) { int maxPrices=0; if(prices.length<2) return 0; for(int i=0;i<prices.length;i++) { for(int j=i+1;j<prices.length;j++) { maxPrices=Math.max(maxPrices,(prices[j]-prices[i])); } } return maxPrices; } }
第二种方法C++:
class Solution { public: int max(int a, int b) { return a > b ? a : b; } int maxProfit(vector<int>& prices) { if (prices.size() < 2) return 0; int maxProfit = 0; int buy = prices[0]; for (int i = 1; i < prices.size(); i++) { if (prices[i] < buy) { buy = prices[i]; } else { maxProfit = max(maxProfit,(prices[i]-buy)); } } return maxProfit; } };
第二种方法Java:
class Solution { public int maxProfit(int[] prices) { if(prices.length<2) return 0; int maxProfit=0; int buy=prices[0]; for(int i=1;i<prices.length;i++) { if(prices[i]<buy) { buy=prices[i]; } else { maxProfit=Math.max(maxProfit,(prices[i]-buy)); } } return maxProfit; } }