leetcode

Solution to some Leetcode problems written in C++
git clone git://git.dimitrijedobrota.com/leetcode.git
Log | Files | Refs | README | LICENSE

1911.cpp (1145B)


      1 
      2 // Standard dp
      3 class Solution {
      4     static long long dp[2][100001];
      5     long long rec(const vector<int> &nums, const int crnt, const bool odd) {
      6         if (crnt >= size(nums)) return 0;
      7         if (dp[odd][crnt] != -1) return dp[odd][crnt];
      8         long long res =
      9             max(rec(nums, crnt + 1, odd), (odd ? -1 : 1) * nums[crnt] + rec(nums, crnt + 1, !odd));
     10         return dp[odd][crnt] = res;
     11     }
     12 
     13   public:
     14     Solution() { memset(dp, 0xFF, sizeof(dp)); }
     15     long long maxAlternatingSum(const vector<int> &nums) { return rec(nums, 0, 0); }
     16 };
     17 
     18 long long Solution::dp[2][100001];
     19 
     20 // Optimized 1
     21 class Solution {
     22   public:
     23     long long maxAlternatingSum(const vector<int> &nums) const {
     24         long long odd = 0, even = 0;
     25         for (const int n : nums) {
     26             even = max(even, odd + n), odd = even - n;
     27         }
     28         return even;
     29     }
     30 };
     31 
     32 // Optimized 2
     33 class Solution {
     34   public:
     35     long long maxAlternatingSum(const vector<int> &nums) const {
     36         long long res = nums[0];
     37         for (int i = 1; i < size(nums); i++) {
     38             res += max(nums[i] - nums[i - 1], 0);
     39         }
     40         return res;
     41     }
     42 };