|
| 1 | +/** |
| 2 | + * Q2. Maximize Subarray Sum (Custom Variation) |
| 3 | + * Medium - ? pt |
| 4 | + * |
| 5 | + * You are given an integer array nums of length n and an integer k. |
| 6 | + * You must select exactly k distinct non-empty subarrays nums[l..r] of nums. |
| 7 | + * Subarrays may overlap, but the exact same subarray (same l and r) cannot be chosen more than once. |
| 8 | + * |
| 9 | + * The value of a subarray nums[l..r] is defined as: |
| 10 | + * max(nums[l..r]) - min(nums[l..r]) |
| 11 | + * |
| 12 | + * The total value is the sum of the values of the selected subarrays. |
| 13 | + * |
| 14 | + * Return the maximum total value you can achieve. |
| 15 | + * |
| 16 | + * Example 1: |
| 17 | + * Input: nums = [1,2,3], k = 2 |
| 18 | + * Output: 4 |
| 19 | + * Explanation: Choose [1,2] with value (2-1)=1 and [2,3] with value (3-2)=1, |
| 20 | + * but better is to pick [1,2,3] with value (3-1)=2 and then repeat logic to maximize → total = 4. |
| 21 | + * |
| 22 | + * ------------------------------------------------------------------ |
| 23 | + * Approach: |
| 24 | + * - To maximize the total, the best difference comes from (global max - global min). |
| 25 | + * - Since you must pick k subarrays, the optimal total is simply (max - min) * k. |
| 26 | + * - This avoids the need to explicitly construct subarrays. |
| 27 | + * |
| 28 | + * ------------------------------------------------------------------ |
| 29 | + * Time Complexity: O(n) |
| 30 | + * (Single scan to compute max and min of nums) |
| 31 | + * |
| 32 | + * Space Complexity: O(1) |
| 33 | + * (Only a few variables used) |
| 34 | + * |
| 35 | + * ------------------------------------------------------------------ |
| 36 | + * LeetCode link: https://leetcode.com/problems/maximize-subarray-sum/ |
| 37 | + */ |
| 38 | + |
| 39 | +class Solution { |
| 40 | + public long maxTotalValue(int[] nums, int k) { |
| 41 | + int max = 0, min = Integer.MAX_VALUE; |
| 42 | + for (int num : nums) { |
| 43 | + max = Math.max(max, num); |
| 44 | + min = Math.min(min, num); |
| 45 | + } |
| 46 | + return (long)(max - min) * k; |
| 47 | + } |
| 48 | +} |
0 commit comments