2640. Find the Score of All Prefixes of an Array
Explanation
To solve this problem, we can iterate over the given array nums
and calculate the score for each prefix as described in the problem statement. We will use a variable maxVal
to keep track of the maximum value encountered so far while iterating. For each element nums[i]
, the score for that prefix will be nums[i] + maxVal
. We update maxVal
whenever we encounter a larger element. The score for the next prefix will include the updated maxVal
.
Algorithm
- Initialize an array
ans
of lengthn
to store the scores for each prefix. - Initialize
maxVal
to 0. - Iterate over the elements of
nums
:- Update
maxVal
to be the maximum of the current element and the previousmaxVal
. - Calculate the score for the current prefix as
nums[i] + maxVal
and store it inans[i]
.
- Update
- Return the
ans
array.
Time Complexity
The time complexity of this algorithm is O(n), where n is the number of elements in the given array nums
.
Space Complexity
The space complexity is O(n) for the ans
array to store the scores.
class Solution {
public int[] getSumAbsoluteDifferences(int[] nums) {
int n = nums.length;
int[] ans = new int[n];
int maxVal = 0;
for (int i = 0; i < n; i++) {
maxVal = Math.max(maxVal, nums[i]);
ans[i] = nums[i] + maxVal;
}
return ans;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.