Maximum Number of Operations With the Same Score I
EasyPrompt
You are given an array of integers nums. Consider the following operation:
- Delete the first two elements
numsand define the score of the operation as the sum of these two elements.
You can perform this operation until nums contains fewer than two elements. Additionally, the same score must be achieved in all operations.
Return the maximum number of operations you can perform.
Example 1:
Input: nums = [3,2,1,4,5]
Output: 2
Explanation:
- We can perform the first operation with the score
3 + 2 = 5. After this operation,nums = [1,4,5]. - We can perform the second operation as its score is
4 + 1 = 5, the same as the previous operation. After this operation,nums = [5]. - As there are fewer than two elements, we can't perform more operations.
Example 2:
Input: nums = [1,5,3,3,4,1,3,2,2,3]
Output: 2
Explanation:
- We can perform the first operation with the score
1 + 5 = 6. After this operation,nums = [3,3,4,1,3,2,2,3]. - We can perform the second operation as its score is
3 + 3 = 6, the same as the previous operation. After this operation,nums = [4,1,3,2,2,3]. - We cannot perform the next operation as its score is
4 + 1 = 5, which is different from the previous scores.
Example 3:
Input: nums = [5,3]
Output: 1
Constraints:
2 <= nums.length <= 1001 <= nums[i] <= 1000
Approaches
2 approaches with complexity analysis and trade-offs.
This approach directly simulates the process described in the problem. We convert the input array to a dynamic list (like ArrayList in Java) to easily remove elements from the front. We perform the first operation, store the score, and then loop, repeatedly removing the first two elements and checking if their sum matches the initial score.
Algorithm
- If the length of the input array
numsis less than 2, return 0. - Convert the
numsarray into ajava.util.Listfor easier element removal. - Remove the first two elements from the list, calculate their sum, and store it as
targetScore. - Initialize an
operationscounter to 1. - Start a
whileloop that continues as long as the list contains at least two elements. - Inside the loop, calculate the sum of the first two elements of the current list.
- If the sum equals
targetScore, increment theoperationscounter and remove the first two elements from the list. - If the sum does not equal
targetScore, break the loop. - After the loop terminates, return the final
operationscount.
Walkthrough
This method provides a straightforward translation of the problem's requirements into code. We begin by handling the edge case where the array is too small for any operations. Then, we convert the array to a List to leverage its dynamic size and removal capabilities. The score of the first operation (sum of the first two elements) sets the targetScore for all subsequent operations. We initialize our operation count to 1. The main logic resides in a while loop that continues as long as we can form a pair of elements. In each iteration, we peek at the sum of the first two elements. If it matches the targetScore, we increment our count and remove them. The critical part is that removing an element from the beginning of an ArrayList is costly because it requires shifting all subsequent elements one position to the left. This leads to a quadratic time complexity, making it unsuitable for large inputs, although it passes for the given constraints.
import java.util.ArrayList;import java.util.List;import java.util.stream.Collectors;import java.util.Arrays; class Solution { public int maxOperations(int[] nums) { if (nums.length < 2) { return 0; } // Convert array to a list for easy removal of elements. List<Integer> numList = new ArrayList<>(); for (int num : nums) { numList.add(num); } // Perform the first operation to set the target score. int first = numList.remove(0); int second = numList.remove(0); int targetScore = first + second; int operations = 1; // Continue performing operations as long as possible. while (numList.size() >= 2) { int currentFirst = numList.get(0); int currentSecond = numList.get(1); if (currentFirst + currentSecond == targetScore) { operations++; // These remove operations are inefficient (O(n) each). numList.remove(0); numList.remove(0); } else { break; } } return operations; }}Complexity
Time
O(n^2) - The `while` loop can run up to `n/2` times. Inside the loop, `remove(0)` on an `ArrayList` takes O(k) time, where `k` is the number of remaining elements. In the worst case, this is O(n). The total time complexity is O(n * n) = O(n^2).
Space
O(n) - We create a new `List<Integer>` that stores a copy of all `n` elements from the input array.
Trade-offs
Pros
The code is a very direct translation of the problem statement, making it easy to understand and reason about.
Cons
Highly inefficient time complexity of O(n^2) due to the nature of
remove(0)on anArrayList.Requires O(n) extra space to create a copy of the array as a list.
A more efficient approach is to avoid modifying the input array altogether. We can iterate through the array using an index, checking pairs of elements sequentially. This avoids the overhead of data structure modifications and achieves a linear time complexity with constant extra space.
Algorithm
- Handle the edge case: If the array
numshas fewer than two elements, return 0. - Calculate the
targetScoreby summing the first two elements,nums[0]andnums[1]. - Initialize an
operationsCountto 1, for the first operation. - Use a
forloop to iterate through the rest of the array, starting from indexi = 2and incrementing by 2 in each step (i += 2). - The loop condition must ensure that we can always access a pair of elements, i.e.,
i + 1 < nums.length. - Inside the loop, calculate the sum of the current pair:
nums[i] + nums[i+1]. - If this sum equals
targetScore, incrementoperationsCount. - If the sum does not equal
targetScore, break the loop immediately. - After the loop finishes, return the final
operationsCount.
Walkthrough
This optimal approach simulates the process without the overhead of actually removing elements from the data structure. We use an index to keep track of which pair of elements we are currently considering. First, we handle the base case where the array has fewer than two elements. We then calculate the targetScore from the first two elements (nums[0] + nums[1]) and count this as our first operation. After that, we iterate through the rest of the array with a for loop, advancing our index by two in each step to move from one pair to the next. The loop starts at index 2 and continues as long as there's a full pair of elements left to check. In each iteration, we sum the current pair and compare it to the targetScore. If they match, we increment our operation count. If at any point the sum doesn't match, we know we cannot continue, so we break the loop. This method is highly efficient as it only requires a single pass over the array.
class Solution { public int maxOperations(int[] nums) { // If the array has fewer than 2 elements, no operations can be performed. if (nums.length < 2) { return 0; } // The score for all operations is determined by the first one. int targetScore = nums[0] + nums[1]; int operationsCount = 1; // Iterate through the rest of the array, two elements at a time. for (int i = 2; i + 1 < nums.length; i += 2) { // Check if the current pair's sum matches the target score. if (nums[i] + nums[i+1] == targetScore) { operationsCount++; } else { // If the score doesn't match, we can't perform any more operations. break; } } return operationsCount; }}Complexity
Time
O(n) - We iterate through the array elements at most once. The loop runs approximately `n/2` times, which is linear in the size of the input array `n`.
Space
O(1) - We only use a few variables (`targetScore`, `operationsCount`, `i`) to store state, which requires constant extra space.
Trade-offs
Pros
Optimal time complexity of O(n).
Optimal space complexity of O(1) as it modifies nothing in-place and uses only a few variables.
Simple, clean, and efficient implementation.
Cons
There are no significant cons to this approach as it is optimal for the given problem.
Solutions
Solution
class Solution {public int maxOperations(int[] nums) { int s = nums[0] + nums[1]; int ans = 0, n = nums.length; for (int i = 0; i + 1 < n && nums[i] + nums[i + 1] == s; i += 2) { ++ans; } return ans; }}class Solution { public: int maxOperations ( vector < int >& nums ) { int s = nums [ 0 ] + nums [ 1 ]; int ans = 0 , n = nums . size (); for ( int i = 0 ; i + 1 < n && nums [ i ] + nums [ i + 1 ] == s ; i += 2 ) { ++ ans ; } return ans ; } };class Solution : def maxOperations ( self , nums : List [ int ]) -> int : s = nums [ 0 ] + nums [ 1 ] ans , n = 0 , len ( nums ) for i in range ( 0 , n , 2 ): if i + 1 == n or nums [ i ] + nums [ i + 1 ] != s : break ans += 1 return ansVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.