题解 | #牛群售价预测# java

牛群售价预测

https://www.nowcoder.com/practice/bbdb8d6f3a2e434e87f749358d16d653

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param prices int整型一维数组
     * @return int整型
     */
    public int max_profit (int[] prices) {
        // write code here
        int maxProfit = 0; // 记录最大利润
        int minPrice = Integer.MAX_VALUE; // 记录最低买入价格

        for (int price : prices) {
            if (price < minPrice) {
                minPrice = price; // 更新最低买入价格
            } else if (price - minPrice > maxProfit) {
                maxProfit = price - minPrice; // 更新最大利润
            }
        }

        return maxProfit;
    }
}

Java 编程语言。

该题考察了以下知识点:

  1. 数组遍历
  2. 贪心算法

代码的文字解释如下:

  • 创建两个变量:maxProfit 用于记录最大利润,minPrice 用于记录当前的最低买入价格。
  • 遍历给定的 prices 数组中的每个元素 price,表示每天牛群的价格。
  • 对于每个价格,如果它小于当前最低买入价格 minPrice,则更新 minPrice 为当前价格,因为牧人应该尽可能低价买入。
  • 否则,如果当前价格减去最低买入价格大于当前最大利润 maxProfit,则更新 maxProfit 为当前利润。这表示如果在当前价格卖出,可以获得更大的利润。
  • 返回 maxProfit,即牧人所能获取的最大利润。
全部评论

相关推荐

03-03 14:35
莆田学院 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务