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

      

  • 相关阅读:
    连通最大子数组和(结对开发)
    第五周学习进度情况
    敏捷开发方法综述
    第四周学习进度情况
    环形数组最大子数组之和
    第四次程序(结对开发)
    第三周学习进度情况
    第三次程序—四则运算(结对开发)
    构建之法阅读笔记02
    按照Right-BICEP要求对实验二进行测试
  • 原文地址:https://www.cnblogs.com/apanda009/p/7953922.html
Copyright © 2011-2022 走看看