Перейти к содержимому

Apply Operations on Array to Maximize Sum of Squares | LeetCode 2897 Daily | Bit Counting

Prateek Goel

0:00 / 0:00

Apply Operations on Array to Maximize Sum of Squares | LeetCode 2897 Daily | Bit Counting

548 просмотров · 1 дн. назад
Prateek Goel
1,68 тыс. подписчиков
548 просмотров · 1 дн. назад
Today's LeetCode Daily (12 Oct 2026): 2897. Apply Operations on Array to Maximize Sum of Squares (Hard), solved three ways, from the first idea to the interview answer. The trick: AND/OR never creates or destroys a bit, it only moves bits between numbers. So the count of ones at each bit position is fixed. Count them once, then greedily build the biggest numbers you can, because squares reward piling the bits together. What you'll learn • Brute force: simulate AND/OR over every pair, O(n²), and why it lands on the right array • Better: count the bits, build every number layer by layer, sort, take the top k • Optimal: build only the k numbers you need straight from the bit counts, O(30 × (n + k)) • The proof that piling bits together beats spreading them out, plus the modulo and edge cases Chapters 0:00 AND/OR only moves bits: the idea 0:23 The problem: the AND/OR operation, k elements, modulo 1:12 Example 1 in binary 1:47 Brute force: simulate every pair 3:26 Brute force code 3:58 Why O(n²) is too slow 4:29 The invariant: bit counts never change 5:29 Why piling bits together wins 6:11 Better: count bits, rebuild, sort 7:17 Better code and complexity 7:54 Optimal: the rows are already sorted 8:29 Walkthrough: build only k numbers 9:09 Optimal code, O(n) 9:48 Optimal complexity, honestly 10:15 Complexity comparison 10:45 Edge cases 11:49 Takeaways Problem: https://leetcode.com/problems/apply-o... Practice the same idea: LeetCode 2275 Largest Combination With Bitwise AND Greater Than Zero · LeetCode 477 Total Hamming Distance More visual DSA walkthroughs: https://growasengineers.com #leetcode #leetcodedaily #dsa #python #codinginterview Narration uses an AI voice.