zoukankan      html  css  js  c++  java
  • find a maximum product triplet in this array

    O(N)扫一遍array就可以了: 找三个最大的, 两个最小的,然后根据第三个最大的正负来判断。

    Approach 4: O(n) Time, O(1) Space

        1. Scan the array and compute Maximum, second maximum and third maximum element present in the array.
        2. Scan the array and compute Minimum and second minimum element present in the array.
        3. Return the maximum of product of Maximum, second maximum and third maximum and product of Minimum, second minimum and Maximum element.

    Note – Step 1 and Step 2 can be done in single traversal of the array.

    int maxProduct(int arr[], int n)
    {
        // if size is less than 3, no triplet exists
        if (n < 3)
            return -1;
     
        // Initialize Maximum, second maximum and third
        // maximum element
        int maxA = INT_MIN, maxB = INT_MIN, maxC = INT_MIN;
     
        // Initialize Minimum and second mimimum element
        int minA = INT_MAX, minB = INT_MAX;
     
        for (int i = 0; i < n; i++)
        {
            // Update Maximum, second maximum and third
            // maximum element
            if (arr[i] > maxA)
            {
                maxC = maxB;
                maxB = maxA;
                maxA = arr[i];
            }
     
            // Update second maximum and third maximum element
            else if (arr[i] > maxB)
            {
                maxC = maxB;
                maxB = arr[i];
            }
     
            // Update third maximum element
            else if (arr[i] > maxC)
                maxC = arr[i];
     
            // Update Minimum and second mimimum element
            if (arr[i] < minA)
            {
                minB = minA;
                minA = arr[i];
            }
     
            // Update second mimimum element
            else if(arr[i] < minB)
                minB = arr[i];
        }
     
        return max(minA * minB * maxA,
                   maxA * maxB * maxC);
    }
    

      

  • 相关阅读:
    如何使用API创建OpenStack虚拟机?
    Windows Server 2012 新特性:IPAM的配置
    DNSSec
    Win Server 8中的利器:微软在线备份服务
    AD RMS总结
    开发中辅助功能
    开发中坑爹的地方
    Js 中常用方法
    asp.net 错误处理
    js中的注意事项(持续整理)
  • 原文地址:https://www.cnblogs.com/apanda009/p/7953922.html
Copyright © 2011-2022 走看看