Leetcode Problem 2561. Rearranging Fruits

2561. Rearranging Fruits

Leetcode Solutions

Swap with Minimum Element Strategy

  1. Create a frequency map for each basket.
  2. Combine the frequency maps and check if all fruits have even counts; if not, return -1.
  3. Find the minimum fruit cost across both baskets.
  4. Subtract the combined frequency map from each basket's frequency map to get the excess fruits.
  5. Sort the excess fruits from both baskets.
  6. Iterate over the sorted excess fruits, calculating the cost of each swap as the minimum of twice the base cost or the fruit cost.
  7. Sum the costs and return the total minimum cost.
UML Thumbnail

Greedy Swap with Sorting

Ask Question

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

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...