触点数字孪生,揭秘它的独特魅力
718
2022-10-09
122. Best Time to Buy and Sell Stock II
Say you have an array 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 (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路: 1、题意为给定一个数组,数组中第i个元素的值对应着第i天的股票,你可以完成多次交易,但是每次交易只能买入一次并卖出,求进行多次交易所能得到的最大利润。该题为Best Time to Buy and Sell Stock的加强版。 2、与Best Time to Buy and Sell Stock类似,该题同样考查的是最大差值。只不过该题考查数组中所有相邻且递增元素的数值之差的总和。只要第i+1天的值大于第i天的值,则可买入,求得利润(差值),遍历整个数组,得到所用差值之和即为总的利润。
class Solution { public int maxProfit(int[] prices) { if (prices == null || prices.length <= 1) return 0; int min = prices[0]; int profit = 0; for (int i = 0; i < prices.length; i++) { if (min > prices[i]) { min = prices[i]; } else { profit += prices[i] - min; min = prices[i]; } } return profit; }}
class Solution { public int maxProfit(int[] prices) { if(prices.length == 0) return 0; int maxProfit = 0; int currentProfit = 0; int buyStock = prices[0]; for(int i=0;i
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。