📜  计算给定操作生成的数组的总和

📅  最后修改于: 2021-09-07 02:05:53             🧑  作者: Mango

给定一个由N 个字符串组成的数组arr[] ,任务是通过在遍历给定数组arr[] 的同时执行以下操作来找到数组brr[] (初始为空)的总和:

  • 如果数组arr[]包含一个整数,则将该整数插入到数组brr[] 中
  • 如果数组arr[]具有字符串“+” ,则将数组brr[] 中最后两个元素的总和插入到数组brr[] 中
  • 如果数组arr[]具有字符串“D” ,则将数组brr[]的最后一个元素的两倍的值插入到数组brr[] 中
  • 如果数组arr[]具有字符串“C” ,则将数组brr[]的最后一个元素移除到数组brr[]

例子:

方法:解决给定问题的想法是使用堆栈。请按照以下步骤解决问题:

  • 初始化一个整数堆栈,比如S ,并初始化一个变量,比如ans0 ,以存储形成的数组的结果总和。
  • 遍历给定的数组arr[]并执行以下步骤:
    • 如果arr[i] 的值为“C” ,则从ans 中减去栈顶元素并从S 中弹出它。
    • 如果ARR的值[i]“d”,然后按堆S的顶部元件两次在堆S然后将其值增加ANS。
    • 如果arr[i] 的值为“+” ,则将堆栈S顶部两个元素之和的值压入栈中,并将它们的和添加到ans
    • 否则,将arr[i]压入堆栈S ,并将其值添加到ans 
  • 循环后,打印ans的值作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
void findTotalSum(vector& ops)
{
    // If the size of array is 0
    if (ops.empty()) {
        cout << 0;
        return;
    }
 
    stack pts;
 
    // Stores the required sum
    int ans = 0;
 
    // Traverse the array ops[]
    for (int i = 0; i < ops.size(); i++) {
 
        // If the character is C, remove
        // the top element from the stack
        if (ops[i] == "C") {
 
            ans -= pts.top();
            pts.pop();
        }
 
        // If the character is D, then push
        // 2 * top element into stack
        else if (ops[i] == "D") {
 
            pts.push(pts.top() * 2);
            ans += pts.top();
        }
 
        // If the character is +, add sum
        // of top two elements from the stack
        else if (ops[i] == "+") {
 
            int a = pts.top();
            pts.pop();
            int b = pts.top();
            pts.push(a);
            ans += (a + b);
            pts.push(a + b);
        }
 
        // Otherwise, push x
        // and add it to ans
        else {
            int n = stoi(ops[i]);
            ans += n;
            pts.push(n);
        }
    }
 
    // Print the resultant sum
    cout << ans;
}
 
// Driver Code
int main()
{
    vector arr = { "5", "-2", "C", "D", "+" };
    findTotalSum(arr);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG
{
 
  // Function to find the sum of the array
  // formed by performing given set of
  // operations while traversing the array ops[]
  static void findTotalSum(String ops[])
  {
 
    // If the size of array is 0
    if (ops.length == 0)
    {
      System.out.println(0);
      return;
    }
 
    Stack pts = new Stack<>();
 
    // Stores the required sum
    int ans = 0;
 
    // Traverse the array ops[]
    for (int i = 0; i < ops.length; i++) {
 
      // If the character is C, remove
      // the top element from the stack
      if (ops[i] == "C") {
 
        ans -= pts.pop();
      }
 
      // If the character is D, then push
      // 2 * top element into stack
      else if (ops[i] == "D") {
 
        pts.push(pts.peek() * 2);
        ans += pts.peek();
      }
 
      // If the character is +, add sum
      // of top two elements from the stack
      else if (ops[i] == "+") {
 
        int a = pts.pop();
        int b = pts.peek();
        pts.push(a);
        ans += (a + b);
        pts.push(a + b);
      }
 
      // Otherwise, push x
      // and add it to ans
      else {
        int n = Integer.parseInt(ops[i]);
        ans += n;
        pts.push(n);
      }
    }
 
    // Print the resultant sum
    System.out.println(ans);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    String arr[] = { "5", "-2", "C", "D", "+" };
    findTotalSum(arr);
  }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Function to find the sum of the array
# formed by performing given set of
# operations while traversing the array ops[]
def findTotalSum(ops):
 
    # If the size of array is 0
    if (len(ops) == 0):
        print(0)
        return
 
    pts = []
 
    # Stores the required sum
    ans = 0
 
    # Traverse the array ops[]
    for i in range(len(ops)):
 
        # If the character is C, remove
        # the top element from the stack
        if (ops[i] == "C"):
 
            ans -= pts[-1]
            pts.pop()
 
        # If the character is D, then push
        # 2 * top element into stack
        elif (ops[i] == "D"):
 
            pts.append(pts[-1] * 2)
            ans += pts[-1]
 
        # If the character is +, add sum
        # of top two elements from the stack
        elif (ops[i] == "+"):
 
            a = pts[-1]
            pts.pop()
            b = pts[-1]
            pts.append(a)
            ans += (a + b)
            pts.append(a + b)
 
        # Otherwise, push x
        # and add it to ans
        else:
            n = int(ops[i])
            ans += n
            pts.append(n)
 
    # Print the resultant sum
    print(ans)
 
# Driver Code
if __name__ == "__main__":
 
    arr = ["5", "-2", "C", "D", "+"]
    findTotalSum(arr)
 
    # This code is contributed by ukasp.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the sum of the array
// formed by performing given set of
// operations while traversing the array ops[]
static void findTotalSum(string []ops)
{
 
    // If the size of array is 0
    if (ops.Length == 0)
    {
        Console.WriteLine(0);
        return;
    }
     
    Stack pts = new Stack();
     
    // Stores the required sum
    int ans = 0;
     
    // Traverse the array ops[]
    for(int i = 0; i < ops.Length; i++)
    {
         
        // If the character is C, remove
        // the top element from the stack
        if (ops[i] == "C")
        {
            ans -= pts.Pop();
        }
         
        // If the character is D, then push
        // 2 * top element into stack
        else if (ops[i] == "D")
        {
            pts.Push(pts.Peek() * 2);
            ans += pts.Peek();
        }
         
        // If the character is +, add sum
        // of top two elements from the stack
        else if (ops[i] == "+")
        {
            int a = pts.Pop();
            int b = pts.Peek();
            pts.Push(a);
            ans += (a + b);
            pts.Push(a + b);
        }
         
        // Otherwise, push x
        // and add it to ans
        else
        {
            int n = Int32.Parse(ops[i]);
            ans += n;
            pts.Push(n);
        }
    }
     
    // Print the resultant sum
    Console.WriteLine(ans);
}
 
// Driver Code
public static void Main()
{
    string []arr = { "5", "-2", "C", "D", "+" };
     
    findTotalSum(arr);
}
}
 
// This code is contributed by ipg2016107


输出:
30

时间复杂度: O(N)
辅助空间: O(N)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live