不限次数进行股票买卖的最大利润 (leetcode 122)
一:解题思路
方法一:不断的寻找股票的最小值和最大值,并在最小值得时候买入,在最大值得时候卖出。Time:O(n),Space:O(1)
方法二:贪心法,只要后一天的值大于前一天的值,那么就进行买卖。Time:O(n),Space:O(1)
两种方法的时间和空间复杂度都是一样的。
二:完整代码示例 (C++版和Java版)
方法一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; } };
方法一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; } }
方法二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; } };
方法二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; } }
Python方法一:
class Solution: def maxProfit(self, prices: List[int]) -> int: n=len(prices) if n==0: return 0 maxProfits=0 i=0 sell=0 buy=0 while i<n-1: while i<n-1 and prices[i+1]<=prices[i]: i+=1 buy=prices[i] while i<n-1 and prices[i+1]>=prices[i]: i+=1 sell=prices[i] maxProfits+=(sell-buy) return maxProfits
Python方法二:
class Solution: def maxProfit(self, prices: List[int]) -> int: n=len(prices) if n==0: return 0 maxProfits=0 for i in range(0,n-1): if prices[i+1]>prices[i]: maxProfits+=(prices[i+1]-prices[i]) return maxProfits

浙公网安备 33010602011771号