Baseball Game

  • 0

    Click here to see the full article post

  • 1

    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];
    switch (s)
    case "+":
    int temp = stack.Pop();
    int n = stack.Peek() + temp;
    sum += n;
    case "D":
    int m = stack.Peek()* 2;
    sum += m;
    case "C":
    sum -= stack.Pop();
    default: //if integer
    sum += int.Parse(s);
    return sum;

  • 0

    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.

  • 0

    @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.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.