Solving Longest Subsequence With Limited Sum using Java and Greedy Algorithm

💡 Day 98 of My DSA Challenge – Longest Subsequence With Limited Sum 🔷 Problem: 2389. Longest Subsequence With Limited Sum 🔷 Goal: For each query, find the maximum number of elements from nums that can form a subsequence with a sum ≤ query value. 🔷 Key Insight: To maximize the subsequence size, we should always pick smaller elements first — this is a greedy choice. Hence, sorting the array ensures we can accumulate the smallest elements until the sum exceeds the query limit. Approach outline: 1️⃣ Sort the array nums. 2️⃣ For each query, add elements one by one until the sum crosses the limit. 3️⃣ Return the count of elements that fit within the limit. This logic can also be optimized further using prefix sums + binary search, but the greedy approach works perfectly within given constraints. 🔷 My Java Approach: Sort the array. Use a helper function to count how many elements fit under the query sum. Store each result in the answer array. 🔷 Complexity: Time → O(n log n + n × m) Space → O(1) Sometimes, simplicity wins. This problem reinforces the power of greedy thinking — starting small, building up gradually, and knowing when to stop. Recognizing such patterns is key to writing clean and intuitive code. 🚀 #100DaysOfCode #Day98 #LeetCode #DSA #Java #ProblemSolving #GreedyAlgorithm #CodingChallenge #Programming #LearnToCode #CodingLife #SoftwareEngineering #Algorithms #DataStructures #TechJourney #CodeEveryday #EngineerMindset #DeveloperJourney #GrowthMindset #CodeNewbie #KeepLearning #ApnaCollege #AlphaBatch #ShraddhaKhapra

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories