Largest element in a list

Question: Write a function that returns the largest item in a list.

Related Tags:

Algorithm

Pretty straight forward. Set max to smallest possible value. Iterate through the list and if there is anything greater than max, then replace. Time complexity is O(n) since we have to iterate through list.

We used an int array here, but you could just as easily implement an ArrayList.

public class Largest {

	public static void main(String[] args) {
		int[] test = {1,3,5,2,3,8,7,4};

		System.out.println(largest(test));
	}

	static int largest(int[] input) {

		int max = Integer.MIN_VALUE;

		for (int i = 0; i < input.length; i++) {

			if (input[i] > max) {
				max = input[i];
			}

		}

		return max;
	}

}

Came up with a better solution or have a question? Comment below!