Skip to content

Conversation

@haset-19
Copy link

@haset-19 haset-19 commented Jun 4, 2022

No description provided.

Copy link

@kyra-patton kyra-patton left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨💫 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.

🟢

Comment on lines +5 to +6
Time Complexity: O(n^2)
Space Complexity: O(1)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✨ 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 ⬇️

Comment on lines +15 to +18
so_far_sum = 0
for each in nums[:index + 1]:
so_far_sum += each
max_so_far = max(so_far_sum, num)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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? 🤔

Suggested change
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)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants