题解 | #牛群买卖计划III#
牛群买卖计划III
https://www.nowcoder.com/practice/47ce4c953769468e8b8b727af3cbebf5
题目考察的知识点是:
动态规划。
题目解答方法的文字分析:
初始化最大利润 ans 为 0,初始化变量 t 为最后一天的价格 prices[n-1]。从倒数第二天开始往前遍历 prices 数组,对于每一天的价格 prices[i],进行如下操作:如果当前价格 prices[i] 比 t 小,说明可以在当天买入并在最后一天卖出,利润为 t-prices[i],将利润累加到 ans 中;否则,更新 t 为当前价格 prices[i],表示重新选择买入的时机。返回最终的结果,表示农场主人能获得的最大利润。
本题解析所用的编程语言:
java语言。
完整且正确的编程代码:
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param prices int整型一维数组 * @return int整型 */ public int maxProfitIII (int[] prices) { // write code here if (prices.length <= 1) { return 0; } int profit = 0; int sell = prices[prices.length - 1]; for (int i = prices.length - 2; i >= 0; i--) { if (prices[i] < sell) { profit += sell - prices[i]; } else { sell = prices[i]; } } return profit; } }#题解#