FastPrepMaximum Value of L (For off-campus 2025 batch hiring :)

Maximum Value of L (For off-campus 2025 batch hiring :)

Uber logoUber● EasyNEW GRADOA

Updated

Problem statement

A magical forest has N trees in a row. Tree i (0 ≤ i < N) has fruits[i] fruits. Your basket holds at most K fruits.

You choose a number L. Then you enter the forest and are teleported to a random tree i. You must collect all the fruits from trees i to i + L - 1, which are L trees in a row. You will always land on a tree where this group fits inside the forest.

You cannot choose where you land. So L only works if every group of L trees in a row has at most K fruits in total.

For example, with fruits [3, 1, 2, 4] and K = 8, the groups of 3 trees have 6 and 7 fruits, so L = 3 works. The group of 4 trees has 10 fruits, so L = 4 does not.

Return the largest L that works. If even a single tree has more than K fruits, return 0.

Function

maximumValueOfL(fruits: int[], k: int) → int

Examples

Example 1

fruits = [3, 1, 2, 4]k = 8return = 3

The row is [3, 1, 2, 4] and the basket holds at most 8 fruits.

Groups of 3 trees: 3 + 1 + 2 = 6 and 1 + 2 + 4 = 7. Both are at most 8, so L = 3 works wherever you land.

The only group of 4 trees has 3 + 1 + 2 + 4 = 10 fruits, which is more than 8, so L = 4 does not work.

The answer is 3.

Constraints

  • 1 ≤ N ≤ 105, where N is fruits.length
  • 1 ≤ fruits[i] ≤ 104
  • 1 ≤ K ≤ 109

More Uber interview questions

Similar questions at other companies

All Uber interview questionsSee Uber hiring insights
Saved
class Solution {
    public int maximumValueOfL(int[] fruits, int k) {
      // write your code here
    }

}
Checking account…