Leetcode Problem 2391. Minimum Amount of Time to Collect Garbage

2391. Minimum Amount of Time to Collect Garbage

Leetcode Solutions

HashMap and Prefix Sum Array

  1. Initialize a prefix sum array prefixSum with the same length as travel plus one, with prefixSum[0] set to 0.
  2. Populate the prefixSum array with the cumulative sum of the travel array.
  3. Initialize a HashMap garbageLastPos to store the last position of each type of garbage.
  4. Initialize a variable totalGarbage to count the total units of garbage.
  5. Iterate over the garbage array, updating garbageLastPos with the last position of each type of garbage and incrementing totalGarbage by the length of each string in garbage.
  6. For each type of garbage ('M', 'P', 'G'), add the travel time to the last position of that garbage type to totalGarbage.
  7. Return totalGarbage as the total time required.
UML Thumbnail

Iterative Calculation with In-place Modification

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...