public class Solution {
public int MaxProduct(int[] nums) {
// first and second highest
var first = 0;
var second = 0;
foreach (var n in nums) {
if (n > first) {
(first, second) = (n, first);
} else if (n > second) {
second = n;
}
}
return (first - 1) * (second - 1);
}
}
Functional Programming:
public class Solution {
public int MaxProduct(int[] nums) =>
nums.OrderByDescending(n => n).Take(2)
.Aggregate((a, b) => (a-1) * (b-1));
}
Source:
https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array/
No comments:
Post a Comment