2011. Final Value of Variable After Performing Operations
UnknownView on LeetCode
Time: O(n)
Space: O(1)
Advertisement
Intuition
Simple accumulation: gain adds to score, lose subtracts. Return maximum score at any point.
Algorithm
- 1For each operation: if gain, score += point. If lose, score -= point. Track max score.
Common Pitfalls
- •Score can go negative but we track maximum at any point, not final score.
2011.cs
C#
// Approach: Count '+' increments and '-' decrements; return difference.
// Time: O(n) Space: O(1)
public class Solution
{
public int FinalValueAfterOperations(string[] operations)
{
int result = 0;
foreach (string operation in operations)
{
if (operation[1] == '+')
result += 1;
else
result -= 1;
}
return result;
}
}Advertisement
Was this solution helpful?