题解 | #小猪摘水果# 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, current = 10; for (int i = 0; i < fruit.length; ++i) { current += fruit[i]; most = Math.max(most, current); } return most; } }
Java编程语言。
该题考察的是数组遍历和数值比较。
代码的文字解释如下:
- 在mostFruitTree方法中,首先定义变量most和current,初始值都为10。其中,most用于记录最多的水果数量,current用于记录当前的累积水果数量。
- 使用循环遍历数组的所有元素。
- 在循环中,将当前元素的值累加到current中,更新current的值。
- 将当前的累积水果数量与之前的最多水果数量most比较,取较大值作为新的最多水果数量。
- 返回最多的水果数量。