Top down DP | | Space optimization(O(1))
\n Describe your approach to solving the problem. \n\n# Complexity\n- Time complexity:O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1
\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    long long maximumTotalCost(vector<int>& nums) {\n        long long ans=0;\n        int n=nums.size();\n        vector<long long> curr(3);\n        vector<long long> prev(3);\n        for(int ind=n-1;ind>=1;ind--){\n            for(int one=1;one>=-1;one-=2){\n                long long ans=0;\n                if(one>0)\n                    ans=max(nums[ind]+prev[-one+1],nums[ind]+prev[one+1]);\n                else\n                    ans=-nums[ind]+prev[-one+1];\n                curr[one+1]=ans;\n            }\n            prev=curr;\n        }\n        return max(curr[0],max(curr[1],curr[2]))+nums[0];\n    }\n};\n```
['C++']