题解 | #小猪摘水果# java
小猪摘水果
https://www.nowcoder.com/practice/fdb76b9170dc4e689a7eceee97159d96
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param fruit int整型一维数组
* @return int整型
*/
public int mostFruitTree (int[] fruit) {
// write code here
int most = 10;
int current = 10;
for (int i = 0; i < fruit.length; ++i) {
current += fruit[i];
most = Math.max(most, current);
if (current < 0) {
current = 0;
}
}
return most;
}
}
使用的是Java语言。
该题考察的知识点是数组的操作和动态规划思想。
代码的文字解释如下:
- 在
mostFruitTree()方法中,我们使用一个循环来遍历给定的水果列表fruit。在每次循环中,将当前水果数量fruit.get(i)加到current变量中,并使用Math.max()方法更新most的值为current和most的较大值。 - 如果
current变成负数,则将其重置为0,表示重新开始计算连续水果数量。 - 返回最大的连续水果数量
most作为结果。

