|
| 1 | +package arrays2; |
| 2 | + |
| 3 | +public class MainClass { |
| 4 | + |
| 5 | + static int containerWithMostWater(int a[]) { |
| 6 | + |
| 7 | + int maxArea = 0; |
| 8 | + int l = 0; |
| 9 | + int r = a.length-1; |
| 10 | + |
| 11 | + while(l < r) { |
| 12 | + int height = Math.min(a[l], a[r]); |
| 13 | + int distance = r-l; |
| 14 | + |
| 15 | + int area = height*distance; |
| 16 | + maxArea = Math.max(maxArea, area); |
| 17 | + |
| 18 | + if(a[l] < a[r]) { |
| 19 | + l++; |
| 20 | + } else { |
| 21 | + r--; |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + return maxArea; |
| 26 | + } |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | + |
| 31 | + |
| 32 | +// {-2, 7, -6, -4, 1, -3, 8}; |
| 33 | +// |
| 34 | +// cur = 8 |
| 35 | +// max = 8 |
| 36 | + |
| 37 | + static int largestSumSubArray(int a[]) { |
| 38 | + |
| 39 | + int curSum = 0; |
| 40 | + int maxSum = Integer.MIN_VALUE; |
| 41 | + |
| 42 | +// int start = |
| 43 | +// int ansStart = |
| 44 | +// int end = |
| 45 | + |
| 46 | + for(int i = 0; i<a.length; i++) { |
| 47 | + curSum += a[i]; |
| 48 | + if(maxSum < curSum) { |
| 49 | + maxSum = curSum; |
| 50 | + //update end |
| 51 | + } |
| 52 | + if(curSum < 0) { |
| 53 | + curSum = 0; |
| 54 | + // reset start = i |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + return maxSum; |
| 59 | + } |
| 60 | + |
| 61 | + |
| 62 | +// |
| 63 | +// largest = 7 |
| 64 | +// 3 4 6 7 |
| 65 | + |
| 66 | + static void leadersinAnArray(int a[]) { |
| 67 | + int largest = Integer.MIN_VALUE; |
| 68 | +// int b[] = new int[a.length]; |
| 69 | +// int j = 0; |
| 70 | + for(int i = a.length-1; i>=0; i--) { |
| 71 | + if(a[i] > largest) { |
| 72 | + largest = a[i]; |
| 73 | + System.out.print(a[i]+" "); |
| 74 | +// b[j++] = a[i]; |
| 75 | + } |
| 76 | + } |
| 77 | +// for(j=j-1; j>=0; j--) { |
| 78 | +// System.out.println(b[j]+" "); |
| 79 | +// } |
| 80 | + } |
| 81 | + |
| 82 | + public static void main(String[] args) { |
| 83 | + |
| 84 | +// int a[] = {-2, -7, -6, -4, -1, -3, -8}; |
| 85 | +// leadersinAnArray(a); |
| 86 | +// int ans = largestSumSubArray(a); |
| 87 | +// |
| 88 | +// System.out.println(ans); |
| 89 | + |
| 90 | + |
| 91 | + int a[] = {1, 8, 6, 2, 4, 5, 8, 3, 7}; |
| 92 | + int ans = containerWithMostWater(a); |
| 93 | + System.out.println(ans); |
| 94 | + } |
| 95 | + |
| 96 | +} |
0 commit comments