Embercode
✕
Divide and ConquerQuick quiz

Majority and subarray

6 questions. Covers Majority element and max subarray.

Questions 1 to 5 of 6

  1. 1. What does this program print? ``cpp #include <algorithm> #include <iostream> #include <limits> #include <span> #include <vector> long long bestAcrossMiddle(std::span<const int> left, std::span<const int> right) { long long bestLeft = std::numeric_limits<long long>::min(); long long run = 0; for (auto it = left.rbegin(); it != left.rend(); ++it) { run += *it; bestLeft = std::max(bestLeft, run); } long long bestRight = std::numeric_limits<long long>::min(); run = 0; for (int x : right) { run += x; bestRight = std::max(bestRight, run); } return bestLeft + bestRight; } int main() { std::vector<int> v = {-4, 6, -1, 2, -7, 3}; std::span<const int> s(v); std::cout << bestAcrossMiddle(s.first(3), s.subspan(3)) << '\n'; } ``
  2. 2. What does this program print? ``cpp #include <algorithm> #include <iostream> #include <span> #include <vector> int countIn(std::span<const int> a, int value) { return static_cast<int>(std::ranges::count(a, value)); } int candidate(std::span<const int> a) { if (a.size() == 1) return a[0]; auto mid = a.size() / 2; int left = candidate(a.first(mid)); int right = candidate(a.subspan(mid)); if (left == right) return left; if (countIn(a, left) > static_cast<int>(a.size() / 2)) return left; return right; } int main() { std::vector<int> nums = {7, 8, 7, 8}; int c = candidate(nums); std::cout << "candidate " << c << ", count " << countIn(nums, c) << '\n'; } ``
  3. 3. Why does majorityElement count the candidate one more time after candidate returns?
  4. 4. In maxSubarray, why does the crossing case need its own check, separate from the two recursive answers?
  5. 5. The combine step below has one wrong line. The rest of the code matches the lesson. ``cpp int candidate(std::span<const int> a) { if (a.size() == 1) return a[0]; auto mid = a.size() / 2; int left = candidate(a.first(mid)); int right = candidate(a.subspan(mid)); if (left == right) return left; if (countIn(a, left) > static_cast<int>(a.size() / 2)) return left; return left; } ` What does majorityElement({2, 1, 1})` return, and what should it return?

5 question(s) left on this page.