Skip to main content

Posts

Chopsticks

Problem Summary You have N sticks, where the i-th stick has length L[i]. You want to form pairs of sticks to be used as chopsticks. Rules: A pair is  usable  if the absolute difference in lengths of the two sticks is  at most  D. Each stick can be used in  at most one  pair. Goal: Find the  maximum number of valid pairs  you can form. Input: First line: two integers N and D. Next N lines: one integer per line, L[i] — length of the i-th stick. Output: One integer: maximum number of usable chopstick pairs. Constraints: 1 <= N <= 10 5 0 <= D <= 10 9 1 <= L[i] <= 10 9 Examples Explanation Input: 5 2 1 3 3 9 4 Output: 2 Sticks lengths: [1, 3, 3, 9, 4], maximum allowed difference D = 2. The stick of length 9 is too far from all others (differences > 2), so it will remain unused. Remaining sticks: 1, 3, 3, 4. One possible optimal pairing: (1, 3)...

Leetcode 84: Largest Rectangle in Histogram

  1. Problem Statement (Simple Explanation) You’re given an array heights where: heights[i] is the height of the i-th bar. Each bar has width 1. You must return the  area of the largest rectangle  that can be formed in the histogram: The rectangle must be  contiguous  (i.e., cover a continuous range of bars). The rectangle’s  height  is limited by the  shortest bar  in that interval. 2. Examples Example 1: Input: heights = [2,1,5,6,2,3] Largest rectangle: Using bars with heights 5 and 6 (indices 2 and 3). Minimum height in that range = 5, width = 2 → area = 5 * 2 = 10. Output: 10 Example 2: Input: heights = [2,4] Best options: Bar 0 alone: area = 2 Bar 1 alone: area = 4 Both bars: min height = 2, width = 2 → area = 4 Max area = 4. Output: 4 3. Approach – Monotonic Stack (O(n)) A brute-force approach (checking all possible ranges) is O(n²) and too slow for n up to 10^5. We use a...