Find the Largest Number in Array
Find the Largest Number in Array
Description:
Find the largest number from an array of integers, considering both positive and negative numbers. Do not use any inbuilt methods for this operation.
Example 1:
Input: arr = [1, 5, -3, 2, 0, -8, 4]
Output: 5
Explanation: The largest number in the array is 5.
Example 2:
Input: arr = [-2, -7, 10, 4, -6, 8]
Output: 10
Explanation: The largest number in the array is 10.
Constraints:
The array length |arr| is at least 1 and at most 10^5. Elements in the array are integers ranging from -10^9 to 10^9.
Java Code:
public class HackerAlgo { public static int findLargestNumber(int[] arr) { if (arr.length == 0) { throw new IllegalArgumentException("Array is empty"); } int max = arr[0]; for (int num : arr) { if (num> max) { max = num; } } return max; } public static void main(String[] args) { int[] exampleArr = {1, 5, -3, 2, 0, -8, 4}; int result = findLargestNumber(exampleArr); System.out.println(result
Python Code:
def find_largest_number(arr): if not arr: raise ValueError("Array is empty") max_num = arr[0] for num in arr: if num>max_num: max_num = num return max_num # Example usage example_arr = [1, 5, -3, 2, 0, -8, 4] result = find_largest_number(example_arr) print(result
C++ Code:
#include <iostream> #include <vector> class HackerAlgo { public: static int findLargestNumber(const std::vector<int>&arr) { if (arr.empty()) { throw std::invalid_argument("Array is empty"); } int max_num = arr[0]; for (int num : arr) { if (num> max_num) { max_num = num; } } return max_num; } }; int main() { // Example usage std::vector<int>exampleArr = {1, 5, -3, 2, 0, -8, 4}; int result = HackerAlgo::findLargestNumber(exampleArr); std::cout<< result << std::endl; return 0
JavaScript Code:
class HackerAlgo { static findLargestNumber(arr) { if (!arr.length) { throw new Error("Array is empty"); } let maxNum = arr[0]; for (let num of arr) { if (num> maxNum) { maxNum = num; } } return maxNum; } } // Example usage constexampleArr = [1, 5, -3, 2, 0, -8, 4]; const result = HackerAlgo.findLargestNumber(exampleArr); console.log(result