A: problem-solving ideas
Method one: constantly looking for the minimum and maximum stock, and the smallest is worth the time to buy and sell at the maximum worth the time. Time: O (n), Space: O (1)
Method Two: greedy, just a day after the value is greater than the value of the previous day, then be traded. Time: O (n), Space: O (n)
Two: Complete code examples (C ++ version and the Java version)
Method one C ++:
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() == 0) return 0; int n = prices.size(); int i = 0, buy = 0, sell = 0,maxProfit=0; while (i < n - 1) { while (i < n - 1 && prices[i + 1] <= prices[i]) i++; buy = prices[i]; while (i < n - 1 && prices[i + 1] >= prices[i]) i++; sell = prices[i]; maxProfit += (sell-buy); } return maxProfit; } };
Method One Java:
class Solution { public int maxProfit(int[] prices) { if(prices==null||prices.length==0) return 0; int maxProfit=0,i=0,buy=0,sell=0; int n=prices.length; while(i<n-1) { while(i<n-1 && prices[i+1]<=prices[i]) i++; buy=prices[i]; while(i<n-1 && prices[i+1]>=prices[i]) i++; sell=prices[i]; maxProfit+=(sell-buy); } return maxProfit; } }
Method Two C ++:
class Solution { public: int maxProfit(vector<int>& prices) { if (prices.size() == 0) return 0; int maxProfit=0; for (int i = 1; i < prices.size(); i++) { if (prices[i] > prices[i - 1]) maxProfit += (prices[i]-prices[i-1]); } return maxProfit; } };
Method Two Java:
class Solution { public int maxProfit(int[] prices) { if(prices==null||prices.length==0) return 0; int maxProfit=0; for(int i=1;i<prices.length;i++) { if(prices[i]>prices[i-1]) maxProfit+=(prices[i]-prices[i-1]); } return maxProfit; } }