3487. Maximum Unique Subarray Sum After Deletion
MediumView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Maximum Unique Subarray Sum After Deletion (Medium) asks you to solve a structured algorithmic task. This is a common Array / Dynamic Programming pattern in coding interviews. If no duplicates, sum all positives; else take max element + all unique positives.
A full step-by-step explanation is being added. See the study guide for pattern-based practice.
Approach
If no duplicates, sum all positives; else take max element + all unique positives.
Related patterns: Array, Dynamic Programming, Sliding Window
3487.cs
C#
// Approach: If no duplicates, sum all positives; else take max element + all unique positives.
// Time: O(n) Space: O(n)
public class Solution
{
public int MaxSum(int[] nums)
{
// Find the maximum value in the array
int max = nums.Max();
// If the maximum value is less than or equal to 0, return it
if (max <= 0)
return max;
// Boolean array to keep track of numbers that have been added to the sum
bool[] seen = new bool[201]; // Assuming numbers are within the range of 0 to 200
int result = 0; // Initialize the sum
// Iterate through each number in the array
foreach (int num in nums)
{
// If the number is negative or has already been added, skip it
if (num < 0 || seen[num])
continue;
// Add the number to the sum and mark it as seen
result += num;
seen[num] = true;
}
// Return the calculated sum
return result;
}
}Was this solution helpful?
Related Problems
- 4. Median of Two Sorted Arrays(Hard)
- 11. Container With Most Water(Medium)
- 15. 3Sum(Medium)
- 16. 3Sum Closest(Medium)
- 22. Generate Parentheses(Medium)
- 26. Remove Duplicates from Sorted Array(Easy)