Click here to see the full article post
Why don't you keep track of sum inside the same for loop instead of having a separate loop afterwards?
public int CalPoints(string ops) //with Stack
Stack<int> stack = new Stack<int>();
int sum = 0;
for (int i = 0; i < ops.Length; i++)
string s = ops[i];
int temp = stack.Pop();
int n = stack.Peek() + temp;
sum += n;
int m = stack.Peek()* 2;
sum += m;
sum -= stack.Pop();
default: //if integer
sum += int.Parse(s);
I wrote a solution using a normal array as a stack.
Taking a sum at the end is essentially fewer operations than keeping track of the sum during the for loop.
My initial submittion with summation at end took 7ms
My second submission with summation in for loop took 9ms.
@yashar My reason wasn't related to waykole's "fewer operations" motivation, I just thought it was a simpler presentation for people trying to read the article and understand.
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.