题解 | #牛群买卖计划III# java
牛群买卖计划III
https://www.nowcoder.com/practice/47ce4c953769468e8b8b727af3cbebf5
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param prices int整型一维数组 * @return int整型 */ public int maxProfitIII (int[] prices) { // write code here int ans = 0; if (prices.length <= 1) { return 0; } int t = prices[prices.length - 1]; for (int i = prices.length - 2; i >= 0; i--) { if (prices[i] < t) { ans += t - prices[i]; } else { t = prices[i]; } } return ans; } }
该代码使用的编程语言是Java。
该题考察的知识点是买卖问题,计算最大利润。
代码的详细文字解释如下:
- 定义一个函数
maxProfitIII
,接受一个整型向量prices
作为参数,表示每天的价格。 - 初始化变量
ans
为0,表示最大利润。 - 如果
prices
的长度小于等于1,即只有一天或没有价格数据,则返回0。 - 将变量
t
初始化为prices
中最后一天的价格。 - 从倒数第二天开始往前遍历
prices
数组,对于每一天的价格prices[i]
,进行如下操作:如果当前价格比t小,说明可以在当天买入并在最后一天卖出,利润为t - prices[i],将利润累加到ans中。否则,更新t为当前价格,表示重新选择买入的时机。 - 遍历结束后,返回最大利润
ans
。