?LeetCode刷題實(shí)戰(zhàn)122:買賣股票的最佳時機(jī) II
Say you have an array prices for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
題意
解題
?本題和上一題相比,唯一的區(qū)別是:這里對買賣次數(shù)沒有限制。

public?int?maxProfit(int[] prices) {
????????//貪心法
????????if(prices==null?|| prices.length==0)
????????????return?0;
????????int?profit=0;
????????for(int?i=1;i????????????if(prices[i]>prices[i-1])
????????????????profit+=(prices[i]-prices[i-1]);
????????}
????????return?profit;
????}
評論
圖片
表情

