[Python] sliding window solution, explained
In this problem we need to find subarray with biggest sum, which has only unique elements. This is in fact almost the same as problem 3. Longest Substring Witho
In this problem we need to find subarray with biggest sum, which has only unique elements. This is in fact almost the same as problem **3. Longest Substring Without Repeating Characters**, but here we need to find sum, not length. But idea is exaclty the same:\n\nLet us keep window with elements `[beg: end)`, where first element is included and last one is not. For example `[0, 0)` is empty window, and `[2, 4)` is window with `2` elements: `2`-th and `3`-th.\n\nLet us discuss our algorithm now:\n\n1. `S` is set of symbols in our window, we use set to check in `O(1)` if new symbol inside it or not.\n2. `beg = end = 0` in the beginning, so we start with empty window, also `ans = 0` and `n = len(nums)` and `sm = 0`: sum of elements in window.\n3. Now, we continue, until one of two of our pointers reaches the end. First, we try to extend our window to the right: check `s[end]` in window and if we can, add it to set, move end pointer to the right and update `sm` and `ans`. If we can not add new symbol to set, it means it is already in window set, and we need to move `beg` pointer to the right, update `sm` and remove elements from `S`.\n\n#### Complexity\nWe move both of our pointers only to the right, so time complexity is `O(n)`. Space complexity is potentially `O(n)` as well.\n\n#### Code\n```python\nclass Solution:\n    def maximumUniqueSubarray(self, nums):\n        beg, end, S, n, sm = 0, 0, set(), len(nums), 0\n        ans = 0\n        while end < n:\n            if nums[end] not in S:\n                sm += nums[end]\n                S.add(nums[end])\n                end += 1\n                ans = max(ans, sm)\n            else:\n                sm -= nums[beg]\n                S.remove(nums[beg])\n                beg += 1\n        \n        return ans \n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
['Two Pointers', 'Sliding Window']