Skip to main content

Command Palette

Search for a command to run...

Maximum Sum With Exactly K Elements

Published
1 min read
Maximum Sum With Exactly K Elements
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.

You are given a 0-indexed integer array nums and an integer k. Your task is to perform the following operation exactly k times in order to maximize your score:

  1. Select an element m from nums.

  2. Remove the selected element m from the array.

  3. Add a new element with a value of m + 1 to the array.

  4. Increase your score by m.

Return the maximum score you can achieve after performing the operation exactly k times.

LeetCode Problem - 2656

class Solution {
    public int maximizeSum(int[] nums, int k) {
        int highestElement = 0; // Initialize a variable to store the highest element in the array

        // Loop through each element in the array to find the highest element
        for(int e : nums) {
            highestElement = Math.max(e, highestElement); // Update highestElement if the current element is greater
        }

        int answer = 0; // Initialize a variable to store the final answer

        // Loop k times to add the highest element and its subsequent values to the answer
        for (int i = 0; i < k; i++) {
            answer += highestElement; // Add the current highest element to the answer
            highestElement++; // Increment the highest element for the next iteration
        }

        return answer; // Return the final answer
    }
}

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.