Problem statement:
Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the given array?
Given an array of positive or negative integer. How will you write an algorithm to find out the largest element in the given array?
- public class LargestElement {
- public static void main(String[] args) {
- int a[] = { 3, 4, 1, 5, 0, -10 };
- int max = Integer.MIN_VALUE; //-2147483648
- for (int i = 0; i < a.length; i++) {
- if (a[i] > max) {
- max = a[i];
- }
- }
- System.out.println("max: " + max);
- }
- }
Output:
max: 5
No comments:
Post a Comment