题解 | #牛群售价预测#

牛群售价预测

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

知识点

贪心

解题思路

定义两个变量:minPrice表示前i天中的最低价格,maxProfit表示前i天中的最大利润。

我们可以从前往后遍历价格数组prices。对于第i天,如果prices[i]比minPrice更低,我们可以更新minPrice的值。如果prices[i]比minPrice更高,我们可以计算当前利润,即prices[i] - minPrice,并更新maxProfit的值。

Java题解

import java.util.*;


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

        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minPrice) {
                minPrice = prices[i];
            } else if (prices[i] - minPrice > maxProfit) {
                maxProfit = prices[i] - minPrice;
            }
        }

        return maxProfit;
    }
}

全部评论

相关推荐

求问!考研下岸,打算参加春招,我这个bg能进啥厂,或者需要搞点深度项目再投吗
Java抽象带篮子_...:直接海投,可以看看我的考研失利速成冲春招贴,里面详细写了简历怎么写,学哪些项目可以速成
点赞 评论 收藏
分享
02-26 09:15
已编辑
蚌埠学院 golang
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务