BackmediumArrays Infosys

Optimizing Warehouse Storage 2 Solution

Problem Statement

Given a prefix of crates and a target sum, find the maximum sum of weights of a subarray starting with the given prefix.

Example 1
Input
[[-3, 5, 7, 2, 1, 3, 4], 12]
Output
20

Explanation: We initialize the maximum sum and the current sum to the first element of the prefix. Then, we iterate through the rest of the prefix, updating the current sum by adding each element and resetting it if it becomes negative. The maximum sum is updated whenever the current sum exceeds it. Finally, we return the maximum sum, which is 20 in this case.

Example 2
Input
[[-5, 6, 3, 1, -2, 4], 7]
Output
7

Explanation: We initialize the maximum sum and the current sum to the first element of the prefix. Then, we iterate through the rest of the prefix, updating the current sum by adding each element and resetting it if it becomes negative. The maximum sum is updated whenever the current sum exceeds it. Finally, we return the maximum sum, which is 7 in this case.

Constraints

  • 1 <= array.length <= 10^5
  • -10^4 <= array[i] <= 10^4
  • 1 <= prefix.length <= 10^5
  • The prefix is a contiguous subarray of the given array
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