Conversation
kyra-patton
left a comment
There was a problem hiding this comment.
✨💫 Nice work Roza! I left a comment on how you might improve your max_subarray solution, but overall I like your implementations! Let me know what questions you have.
🟢
| Time Complexity: O(n^2) | ||
| Space Complexity: O(1) |
There was a problem hiding this comment.
✨ This works and your time and space complexity does match your solution, but I think you're doing a little extra work here and we can make this solution even more efficient! See comments below ⬇️
| so_far_sum = 0 | ||
| for each in nums[:index + 1]: | ||
| so_far_sum += each | ||
| max_so_far = max(so_far_sum, num) |
There was a problem hiding this comment.
With your current solution, you calculate what the sum would be for values from index 0 to the current index, and set 'max_so_far' to be either that calculated value or the current value you are iterating over.
We can eliminate the need for that inner loop/calculation by instead just checking if max_so_far + the next value in the list is greater than the next value in the list. If max_so_far + num is greater than num, max_so_far in the next iteration will already hold the so_far_sum value you're currently calculating with a loop.
If max_so_far + num is less than num, that means the so_far_sum shouldn't be a part of the subarray anyways, so there's no need to calculate it in this case either.
How would this change to your code affect your time and space complexity? 🤔
| so_far_sum = 0 | |
| for each in nums[:index + 1]: | |
| so_far_sum += each | |
| max_so_far = max(so_far_sum, num) | |
| max_so_far = max(max_so_far + num, num) |
| Time Complexity: ? | ||
| Space Complexity: ? | ||
| Time Complexity: O(n) | ||
| Space Complexity: O(n) |
No description provided.