Sunday, March 14, 2021

Leetcode Everyday: 1464. Maximum Product of Two Elements in an Array. Easy

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);
    }
}
Funtional 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