Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the maximum sum with the first element of the array.
DSA Rust
let mut max_so_far = [1];Attempts:
3 left
💡 Hint
Common Mistakes
Initializing max_so_far to 0 causes incorrect results if all numbers are negative.
Using nums.len() is incorrect because it gives the length, not a value from the array.
✗ Incorrect
We start max_so_far with the first element to handle arrays with all negative numbers correctly.
2fill in blank
mediumComplete the code to update the current maximum subarray sum ending at index i.
DSA Rust
current_max = std::cmp::max(nums[i], current_max [1] nums[i]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication changes the logic and breaks the algorithm.
Using division is not meaningful in this context.
✗ Incorrect
We add nums[i] to current_max or start fresh from nums[i], whichever is larger.
3fill in blank
hardFix the error in updating the global maximum sum after processing each element.
DSA Rust
max_so_far = std::cmp::max(max_so_far, [1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using nums[i] alone ignores previous sums.
Adding max_so_far and nums[i] is incorrect for max tracking.
✗ Incorrect
We update max_so_far with the maximum of itself and current_max, which holds the max subarray sum ending at i.
4fill in blank
hardFill both blanks to complete the loop that iterates over the array starting from the second element.
DSA Rust
for i in [1]..[2] { // loop body }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting from 0 causes double processing of the first element.
Using nums.len() - 1 excludes the last element.
✗ Incorrect
We start from index 1 and go up to nums.len() to cover all elements after the first.
5fill in blank
hardFill all three blanks to complete the function that returns the maximum subarray sum using Kadane's algorithm.
DSA Rust
fn max_subarray_sum(nums: Vec<i32>) -> i32 {
let mut max_so_far = nums[0];
let mut current_max = nums[0];
for i in [1]..[2] {
current_max = std::cmp::max(nums[i], current_max [3] nums[i]);
max_so_far = std::cmp::max(max_so_far, current_max);
}
max_so_far
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction instead of addition breaks the logic.
Incorrect loop bounds cause index errors or missed elements.
✗ Incorrect
Start loop from 1 to nums.len(), update current_max by adding nums[i] or starting fresh at nums[i].
