702704. Mega Sale

Basic

Here is the detailed Markdown blog post for the "Mega Sale" problem:

Mega Sale

Summary

The Mega Sale problem involves finding the maximum sum of k consecutive elements in an array. This problem requires a solid understanding of arrays, sorting, and algorithms. The goal is to identify the best possible sequence of k elements that add up to the highest total value.

Detailed Explanation

To tackle this problem, we can use a two-step approach: first, sort the array in descending order based on the values, and then find the maximum sum of k consecutive elements.

Here's a step-by-step breakdown of the solution:

  1. Sort the array arr in descending order:

    arr.sort((a, b) => b - a);
    
  2. Initialize two variables: max_sum to store the maximum sum found so far and window_sum to keep track of the sum of the current window:

    int max_sum = 0;
    int window_sum = 0;
    
  3. Iterate over the sorted array using a sliding window approach:

    for (int i = 0; i < arr.length; i++) {
        // Add the current element to the window sum
        window_sum += arr[i];
        
        // If the window size is greater than k, subtract the first element of the previous window
        if (i >= k) {
            window_sum -= arr[i - k];
        }
        
        // Update the maximum sum if the current window sum is higher
        max_sum = Math.max(max_sum, window_sum);
    }
    
  4. Return the max_sum as the result:

    return max_sum;
    

The time complexity of this algorithm is O(n log n) due to the sorting operation, where n is the length of the array. The space complexity is O(1), as we only use a constant amount of space.

Optimized Solutions

Java

View on GeeksforGeeks
public class MegaSale {
    public static int maxSum(int[] arr, int k) {
        Arrays.sort(arr);
        int max_sum = 0;
        int window_sum = 0;

        for (int i = 0; i < arr.length; i++) {
            window_sum += arr[i];

            if (i >= k) {
                window_sum -= arr[i - k];
            }

            max_sum = Math.max(max_sum, window_sum);
        }

        return max_sum;
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.