Skip to main content

Command Palette

Search for a command to run...

K Items With the Maximum Sum

Published
2 min read
K Items With the Maximum Sum
G

As a Systems Engineer at Tata Consultancy Services, I deliver exceptional software products for mobile and web platforms, using agile methodologies and robust quality maintenance. I am experienced in performance testing, automation testing, API testing, and manual testing, with various tools and technologies such as Jmeter, Azure LoadTest, Selenium, Java, OOPS, Maven, TestNG, and Postman.

I have successfully developed and executed detailed test plans, test cases, and scripts for Android and web applications, ensuring high-quality standards and user satisfaction. I have also demonstrated my proficiency in manual REST API testing with Postman, as well as in end-to-end performance and automation testing using Jmeter and selenium with Java, TestNG and Maven. Additionally, I have utilized Azure DevOps for bug tracking and issue management.

There is a bag that consists of items, each item has a number 1, 0, or -1 written on it.

You are given four non-negative integers numOnes, numZeros, numNegOnes, and k.

The bag initially contains:

  • numOnes items with 1s written on them.

  • numZeroes items with 0s written on them.

  • numNegOnes items with -1s written on them.

We want to pick exactly k items among the available items. Return the maximum possible sum of numbers written on the items.

LeetCode Problem - 2600

class Solution {
    public int kItemsWithMaximumSum(int numOnes, int numZeros, int numNegOnes, int k) {
        int result = 0; // Initialize result to store the sum of selected items.

        // Process 'k' items to maximize the sum.
        while (k > 0) {
            if (numOnes > 0) {
                // If there are '1's available, add 1 to the result and decrease their count.
                result++;
                numOnes--;
            } else if (numZeros > 0) {
                // If no '1's are left but there are '0's, simply decrement their count.
                // Adding 0 does not change the result.
                numZeros--;
            } else {
                // If no '1's or '0's are left, use '-1's.
                // Subtract 1 from the result and decrease the count of '-1's.
                result--;
                numNegOnes--;
            }
            k--; // Decrease the count of items to process.
        }

        return result; // Return the final maximum sum.
    }
}

More from this blog

S

Software and Performance Testing Insights

462 posts

Results-Driven Agile QA Specialist | Expert in Mobile & Web Testing | Proficient in Test Planning, Execution, and Root Cause Analysis.

K Items With the Maximum Sum