题解 | #牛群的能量#

牛群的能量

https://www.nowcoder.com/practice/00f87ddcd18842d0824d487fd70a730e

考察对于题目的理解能力,感觉主要还是数组上的应用。

其实对于连续的序列,只有这段序列中新加入的只能够让序列和为正数的时候才会考虑将新的值加入到序列中去以满足最长,并且在这个过程中保留其中的最大值,直到说新加入的值使得序列和为负数时,说明需要重新开始计算序列。

完整Java代码如下所示

import java.util.*;


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

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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