How to find the largest number in an array that is at least twice as large as others

🚀 Day 38 of #100DaysOfCode – LeetCode Problem #747: Largest Number At Least Twice of Others 💡 Problem Summary: Given an integer array nums, find whether the largest number is at least twice as large as all other numbers. If it is, return the index of the largest element; otherwise, return -1. 📘 Example: Input: nums = [3,6,1,0] Output: 1 Input: nums = [1,2,3,4] Output: -1 🧠 Approach: Find the largest and second largest numbers in the array. If largest >= 2 * secondLargest, return the index of the largest. Otherwise, return -1. 💻 Java Solution: class Solution { public int dominantIndex(int[] nums) { int max = -1, second = -1, index = -1; for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { second = max; max = nums[i]; index = i; } else if (nums[i] > second) { second = nums[i]; } } return second * 2 <= max ? index : -1; } } ⚙️ Complexity: Time: O(n) Space: O(1) ✅ Result: Accepted (Runtime: 0 ms) 🎯 Key Takeaway: Sometimes, solving problems isn’t about complex algorithms — it’s about thinking clearly and tracking key elements efficiently.

To view or add a comment, sign in

Explore content categories