BackmediumArrays Salesforce

Galactic Resource Allocation 2 Solution

Problem Statement

Given an array of resource quantities and a target capacity, find the longest subarray where the total resource quantity is less than or equal to the target capacity.

Example 1
Input
[3, 2, 4, 1, 2, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Output
4

Explanation: Step-by-step: Given the input array [3, 2, 4, 1, 2, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], we first initialize two pointers, left and right, to the start of the array. We then calculate the sum of the subarray from the left pointer to the right pointer. If the sum is less than or equal to the target capacity, we increment the right pointer and update the maximum length of the subarray. If the sum is greater than the target capacity, we increment the left pointer and update the maximum length of the subarray. The maximum length of the subarray is then returned as the output.

Example 2
Input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Output
5

Explanation: Step-by-step: Given the input array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], we first initialize two pointers, left and right, to the start of the array. We then calculate the sum of the subarray from the left pointer to the right pointer. If the sum is less than or equal to the target capacity, we increment the right pointer and update the maximum length of the subarray. If the sum is greater than the target capacity, we increment the left pointer and update the maximum length of the subarray. The maximum length of the subarray is then returned as the output.

Constraints

  • 1 <= resources.length <= 10^5
  • 1 <= resources[i] <= 10^3
  • 1 <= targetCapacity <= 10^6
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free