题解 | #牛群售价预测#

牛群售价预测

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

知识点:贪心

我们要想获得最大的利润,就需要找到当前最小的元素,再用当前位置的元素减去最小的元素值,即为利润,要想利润最大,就需要保证我们的成本保持在最小值,通过不断更新最小成本,来尝试获取每个位置能得到的最大利润。

Java题解如下

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param prices int整型一维数组 
     * @return int整型
     */
    public int max_profit (int[] prices) {
        // write code here
        int n = prices.length;
        int profit = 0;
        int min = prices[0];
        for(int i = 1; i < n; i++) {
            profit = Math.max(profit, prices[i] - min);
            if(prices[i] < min) {
                min = prices[i];
            }
        }
        return profit;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-09 12:11
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-11 11:30
点赞 评论 收藏
分享
06-02 15:53
阳光学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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