fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. typedef long long int ll;
  4.  
  5. ll max(ll a,ll b,ll c) //max of 3nums- used in main()
  6. {
  7. return max(a,max(b,c));
  8. }
  9. ll min(ll a,ll b,ll c) //min of 3 nums- used in main()
  10. {
  11. return min(a,min(b,c));
  12. }
  13.  
  14. int main() {
  15. int b; cin>>b; //no of queries
  16. ll dp1[b+1]; //dp1 stores max value till index i
  17. ll dp2[b+1]; //dp2 stores min val till i
  18. //2 arrays being used since in operations like negation, value can min->max and vice-versa
  19. dp1[0]=1;
  20. dp2[0]=dp1[0];
  21. for(int i=1;i<=b;i++){
  22. char g; cin>>g; //input sign
  23. ll e;
  24. if (g=='+' || g == '-' || g == '*' || g == '/') cin >> e; //input numeric
  25. if (g =='+') {
  26. //we take max of {adding curr element to dp1[i-1], or dp2[i-1], or
  27. //NOT selecting the i-1 index of dp1/ dp2 in curr element}
  28. dp1[i] = max(dp1[i - 1] + e, dp2[i - 1] + e, dp1[i - 1]);
  29. dp2[i] = min(dp1[i - 1] + e, dp2[i - 1] + e, dp2[i - 1]);}
  30. else if (g == '-') {
  31. dp1[i] = max(dp1[i - 1] - e, dp2[i - 1] - e, dp1[i - 1]);
  32. dp2[i] = min(dp1[i - 1] - e, dp2[i - 1] - e, dp2[i - 1]);
  33. }
  34. else if (g == '*') {
  35. dp1[i] = max(dp1[i - 1] * e, dp2[i - 1] * e, dp1[i - 1]);
  36. dp2[i] = min(dp1[i - 1] * e, dp2[i - 1] * e, dp2[i - 1]);
  37. }
  38. else if (g == '/') {
  39. dp1[i] = max(dp1[i-1]/e,dp2[i-1]/e,dp1[i-1]) ;
  40. dp2[i] = min(dp1[i-1]/e,dp2[i-1]/e,dp2[i-1]) ;
  41. }
  42. else {
  43. dp1[i] = max(-dp1[i - 1], -dp2[i - 1], dp1[i - 1]);
  44. dp2[i] = min(-dp1[i - 1], -dp2[i - 1], dp2[i - 1]);
  45. }
  46.  
  47. }
  48.  
  49. cout << dp1[b] << "\n";
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0.01s 5288KB
stdin
4
+ 3
* -2
~ 
+ 4
stdout
12