Given an array arr[] of size N and three numbers P, Q, and R. The task is to find three indices named (i, j, k) in the given array such that i < j < k, and the value of equation (P * arr[i] + Q * arr[j] + R * arr[k]) should be maximum.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}, P = 1, Q = 2, R = 3
Output: 2 3 4
Explanation: For the given array the possible triplets and their sums are as given following:
(1, 2, 3): 1 * 1 + 2 * 2 + 3 * 3 = 1 + 4 + 9 = 14
(1, 2, 4): 1 * 1 + 2 * 2 + 4 * 3 = 1 + 4 + 12 = 17
(1, 2, 5): 1 * 1 + 2 * 2 + 5 * 3 = 1 + 4 + 15 = 20
(1, 3, 4): 1 * 1 + 3 * 2 + 4 * 3 = 1 + 6 + 12 = 19
(1, 3, 5): 1 * 1 + 3 * 2 + 5 * 3 = 1 + 6 + 15 = 22
(1, 4, 5): 1 * 1 + 4 * 2 + 5 * 3 = 1 + 8 + 15 = 24
(2, 3, 4): 2 * 1 + 3 * 2 + 4 * 3 = 2 + 6 + 12 = 20
(2, 3, 5): 2 * 1 + 3 * 2 + 5 * 3 = 2 + 6 + 15 = 23
(2, 4, 5): 2 * 1 + 4 * 2 + 5 * 3 = 2 + 8 + 15 = 25
(3, 4, 5): 3 * 1 + 4 * 2 + 5 * 3 = 3 + 8 + 15 = 26
26 is the maximum sum for triplet 3, 4, 5. Therefore, the answer will be 2, 3, 4 which are the corresponding indices of 3,4,5 in given array.Input: arr[] = {2, 1, 5, 4, 3}, P = 2, Q = 1, R = 3
Output: 2 3 4
Explanation:
For the given array the possible triplets and their sums are as given following:
(2, 1, 5): 2 * 2 + 1 * 1 + 5 * 3 = 4 + 1 + 15 = 20
(2, 1, 4): 2 * 2 + 1 * 1 + 4 * 3 = 4 + 1 + 12 = 17
(2, 1, 3): 2 * 2 + 5 * 1 + 4 * 3 = 4 + 5 + 12 = 21
(2, 5, 3): 2 * 2 + 5 * 1 + 3 * 3 = 4 + 5 + 9 = 18
(2, 4, 3): 2 * 2 + 4 * 1 + 3 * 3 = 4 + 4 + 9 = 17
(1, 5, 4): 1 * 2 + 5 * 1 + 4 * 3 = 2 + 5 + 12 = 19
(1, 5, 3): 1 * 2 + 5 * 1 + 3 * 3 = 2 + 5 + 9 = 16
(1, 4, 3): 1 * 2 + 4 * 1 + 3 * 3 = 2 + 4 + 9 = 15
(5, 4, 3): 5 * 2 + 4 * 1 + 3 * 3 =10 + 4 + 9 = 23
23 is the maximum sum for triplet 5, 4, 3. Therefore, the answer will be (2, 3, 4), which are the corresponding indices of 5, 4, 3 in the given array.
Approach: Brute force
In this approach idea is we will check each triplet that can be formed by using 3 nested loops. The outer loop will track position of i which can be vary from 0 to n-1 (n is size of given array), the second loop will track value of j which will vary from i+1 to n-1 and the inner loop will track value of k which will vary from j+1 to n-1. By doing this we can check value of the given equation for each and every triplet that can be formed by using this array.
Below is the implementation of the above approach:
#include <bits/stdc++.h> using namespace std;
// Function to find the triplets with maximum weighted sum vector< int > findMaxWeightedTriplets(vector< int >& arr, int P,
int Q, int R)
{ int n = arr.size();
// Initialize a vector to store the result (indices of
// the triplets)
vector< int > result(3, 0);
// Initialize the maximum weighted sum to the minimum
// possible value
int maxWeight = INT_MIN;
// Loop through all possible triplets in the array
for ( int i = 0; i < n - 2; i++) {
for ( int j = i + 1; j < n - 1; j++) {
for ( int k = j + 1; k < n; k++) {
// Calculate the weighted sum for the
// current triplet
int currentWeight
= P * arr[i] + Q * arr[j] + R * arr[k];
// Update the result if the current weighted
// sum is greater than the current maximum
if (currentWeight > maxWeight) {
maxWeight = currentWeight;
result[0] = i;
result[1] = j;
result[2] = k;
}
}
}
}
// Return the indices of the triplets with maximum
// weighted sum
return result;
} // Main function int main()
{ vector< int > arr = { 1, 2, 3, 4, 5 };
int P = 1, Q = 2, R = 3;
// Call the function to find the triplets with maximum
// weighted sum
vector< int > result
= findMaxWeightedTriplets(arr, P, Q, R);
// Print the result
cout << result[0] << " " << result[1] << " "
<< result[2] << endl;
return 0;
} |
public class MaxWeightedTriplets {
// Function to find the indices of triplets with maximum
// weighted sum
public static int [] findMaxWeightedTriplets( int [] arr,
int P,
int Q,
int R)
{
int n = arr.length;
// Initialize an array to store the result (indices
// of the triplets)
int [] result = new int [ 3 ];
// Initialize the maximum weighted sum to the
// minimum possible value
int maxWeight = Integer.MIN_VALUE;
// Nested loops to iterate through all possible
// triplets in the array
for ( int i = 0 ; i < n - 2 ; i++) {
for ( int j = i + 1 ; j < n - 1 ; j++) {
for ( int k = j + 1 ; k < n; k++) {
// Calculate the weighted sum for the
// current triplet
int currentWeight = P * arr[i]
+ Q * arr[j]
+ R * arr[k];
// Update the result if the current
// weighted sum is greater than the
// current maximum
if (currentWeight > maxWeight) {
maxWeight = currentWeight;
result[ 0 ] = i;
result[ 1 ] = j;
result[ 2 ] = k;
}
}
}
}
// Return the indices of the triplets with maximum
// weighted sum
return result;
}
// Main method
public static void main(String[] args)
{
int [] arr = { 1 , 2 , 3 , 4 , 5 };
int P = 1 , Q = 2 , R = 3 ;
// Call the function to find the triplets with
// maximum weighted sum
int [] result
= findMaxWeightedTriplets(arr, P, Q, R);
// Print the result
System.out.println(result[ 0 ] + " " + result[ 1 ] + " "
+ result[ 2 ]);
}
} |
def find_max_weighted_triplets(arr, P, Q, R):
n = len (arr)
# Initialize a list to store the result (indices of the triplets)
result = [ 0 , 0 , 0 ]
# Initialize the maximum weighted sum to negative infinity
max_weight = float ( '-inf' )
# Nested loops to iterate through all possible triplets in the array
for i in range (n - 2 ):
for j in range (i + 1 , n - 1 ):
for k in range (j + 1 , n):
# Calculate the weighted sum for the current triplet
current_weight = P * arr[i] + Q * arr[j] + R * arr[k]
# Update the result if the current weighted sum is greater than the current maximum
if current_weight > max_weight:
max_weight = current_weight
result[ 0 ] = i
result[ 1 ] = j
result[ 2 ] = k
return result
# Example usage arr = [ 1 , 2 , 3 , 4 , 5 ]
P, Q, R = 1 , 2 , 3
# Call the function to find the triplets with maximum weighted sum output = find_max_weighted_triplets(arr, P, Q, R)
# Print the result print (f"{output[ 0 ]} {output[ 1 ]} {output[ 2 ]}")
|
using System;
using System.Collections.Generic;
public class Program
{ // Function to find the triplets with maximum weighted sum
public static List< int > FindMaxWeightedTriplets(List< int > arr, int P, int Q, int R)
{
int n = arr.Count;
// Initialize a list to store the result (indices of the triplets)
List< int > result = new List< int > { 0, 0, 0 };
// Initialize the maximum weighted sum to the minimum possible value
int maxWeight = int .MinValue;
// Loop through all possible triplets in the array
for ( int i = 0; i < n - 2; i++)
{
for ( int j = i + 1; j < n - 1; j++)
{
for ( int k = j + 1; k < n; k++)
{
// Calculate the weighted sum for the current triplet
int currentWeight = P * arr[i] + Q * arr[j] + R * arr[k];
// Update the result if the current weighted sum is greater than the current maximum
if (currentWeight > maxWeight)
{
maxWeight = currentWeight;
result[0] = i;
result[1] = j;
result[2] = k;
}
}
}
}
// Return the indices of the triplets with maximum weighted sum
return result;
}
// Main function
public static void Main()
{
List< int > arr = new List< int > { 1, 2, 3, 4, 5 };
int P = 1, Q = 2, R = 3;
// Call the function to find the triplets with maximum weighted sum
List< int > result = FindMaxWeightedTriplets(arr, P, Q, R);
// Print the result
Console.WriteLine($ "{result[0]} {result[1]} {result[2]}" );
}
} // This code is contributed by shivamgupta0987654321 |
<script> // Function to find the triplets with maximum weighted sum function findMaxWeightedTriplets(arr, P, Q, R) {
let n = arr.length;
// Initialize an array to store the result (indices of the triplets)
let result = [0, 0, 0];
// Initialize the maximum weighted sum to the minimum possible value
let maxWeight = Number.MIN_SAFE_INTEGER;
// Loop through all possible triplets in the array
for (let i = 0; i < n - 2; i++) {
for (let j = i + 1; j < n - 1; j++) {
for (let k = j + 1; k < n; k++) {
// Calculate the weighted sum for the current triplet
let currentWeight = P * arr[i] + Q * arr[j] + R * arr[k];
// Update the result if the current weighted sum is greater than the current maximum
if (currentWeight > maxWeight) {
maxWeight = currentWeight;
result[0] = i;
result[1] = j;
result[2] = k;
}
}
}
}
// Return the indices of the triplets with maximum weighted sum
return result;
} // Main function function main() {
let arr = [1, 2, 3, 4, 5];
let P = 1, Q = 2, R = 3;
// Call the function to find the triplets with maximum weighted sum
let result = findMaxWeightedTriplets(arr, P, Q, R);
// Print the result
console.log(`${result[0]} ${result[1]} ${result[2]}`);
} // Call the main function main(); </script> |
2 3 4
Time Complexity: O(N3), where N is the size of the given array arr[].
Auxiliary Space: O(1)
Efficient Approach:
We can observe that instead of calculating the value for every possible pair, we can go to each index and multiply it with Q and the numbers to be multiplied with P and R will be maximum number on left of selected index and maximum number on right of selected number respectively. If we do this for every index, we can get the indices with maximum values.
Step-by-step algorithm:
- Initiate two arrays of size equal to arr[].
- For each index in array calculate the maximum element on left of the index and Maximum element on right of the index.
- Iterate through each index and calculate value of given equation as P*leftMax + Q*index + R* rightMax.
- Store the indices whenever we get sum greater the previous sum.
#include <bits/stdc++.h> #include <climits> using namespace std;
int * find_max_weighted_triplets( int arr[], int P, int Q,
int R, int n)
{ int * indices = new int [3];
int * leftMax = new int [n];
int * rightMax = new int [n];
// Initialize leftMax and rightMax arrays
leftMax[0] = 0;
rightMax[n - 1] = n - 1;
// Fill leftMax and rightMax arrays
for ( int i = 1; i < n; i++) {
leftMax[i] = (arr[i] > arr[leftMax[i - 1]])
? i
: leftMax[i - 1];
}
for ( int i = n - 2; i >= 0; i--) {
rightMax[i] = (arr[i] > arr[rightMax[i + 1]])
? i
: rightMax[i + 1];
}
// Traverse array to find maximum j and sum
int maxSum = INT_MIN;
for ( int j = 1; j < n - 1; j++) {
int currSum = P * arr[leftMax[j - 1]] + Q * arr[j]
+ R * arr[rightMax[j + 1]];
if (currSum > maxSum) {
maxSum = currSum;
indices[0] = leftMax[j - 1];
indices[1] = j;
indices[2] = rightMax[j + 1];
}
}
delete [] leftMax;
delete [] rightMax;
return indices;
} int main()
{ int arr[] = { 1, 2, 3, 4, 5 };
int P = 1, Q = 2, R = 3;
int n = sizeof (arr) / sizeof (arr[0]);
int * result
= find_max_weighted_triplets(arr, P, Q, R, n);
cout << result[0] << " " << result[1] << " "
<< result[2] << endl;
delete [] result;
return 0;
} |
public class Main {
public static void main(String[] args) {
int [] arr = { 1 , 2 , 3 , 4 , 5 };
int P = 1 , Q = 2 , R = 3 ;
int [] result = find_max_weighted_triplets(arr, P, Q, R);
System.out.println(result[ 0 ] + " " + result[ 1 ] + " " + result[ 2 ]);
}
public static int [] find_max_weighted_triplets( int [] arr, int P, int Q, int R) {
int n = arr.length;
int [] leftMax = new int [n];
int [] rightMax = new int [n];
// Initialize leftMax and rightMax arrays
leftMax[ 0 ] = 0 ;
rightMax[n - 1 ] = n - 1 ;
// Fill leftMax and rightMax arrays
for ( int i = 1 ; i < n; i++) {
leftMax[i] = (arr[i] > arr[leftMax[i - 1 ]]) ? i : leftMax[i - 1 ];
}
for ( int i = n - 2 ; i >= 0 ; i--) {
rightMax[i] = (arr[i] > arr[rightMax[i + 1 ]]) ? i : rightMax[i + 1 ];
}
// Traverse array to find maximum j and sum
int maxSum = Integer.MIN_VALUE;
int [] indices = new int [ 3 ];
for ( int j = 1 ; j < n - 1 ; j++) {
int currSum = P * arr[leftMax[j - 1 ]] + Q * arr[j] + R * arr[rightMax[j + 1 ]];
if (currSum > maxSum) {
maxSum = currSum;
indices[ 0 ] = leftMax[j - 1 ];
indices[ 1 ] = j;
indices[ 2 ] = rightMax[j + 1 ];
}
}
return indices;
}
} |
def find_max_weighted_triplets(arr, P, Q, R):
n = len (arr)
indices = [ 0 , 0 , 0 ]
left_max = [ 0 ] * n
right_max = [ 0 ] * n
# Initialize left_max and right_max arrays
left_max[ 0 ] = 0
right_max[n - 1 ] = n - 1
# Fill left_max and right_max arrays
for i in range ( 1 , n):
left_max[i] = i if arr[i] > arr[left_max[i - 1 ]] else left_max[i - 1 ]
for i in range (n - 2 , - 1 , - 1 ):
right_max[i] = i if arr[i] > arr[right_max[i + 1 ]
] else right_max[i + 1 ]
# Traverse array to find maximum j and sum
max_sum = float ( '-inf' )
for j in range ( 1 , n - 1 ):
current_sum = P * arr[left_max[j - 1 ]] + \
Q * arr[j] + R * arr[right_max[j + 1 ]]
if current_sum > max_sum:
max_sum = current_sum
indices = [left_max[j - 1 ], j, right_max[j + 1 ]]
return indices
arr = [ 1 , 2 , 3 , 4 , 5 ]
P, Q, R = 1 , 2 , 3
result = find_max_weighted_triplets(arr, P, Q, R)
print (f"{result[ 0 ]} {result[ 1 ]} {result[ 2 ]}")
|
using System;
class Program
{ static int [] FindMaxWeightedTriplets( int [] arr, int P, int Q, int R, int n)
{
int [] indices = new int [3];
int [] leftMax = new int [n];
int [] rightMax = new int [n];
// Initialize leftMax and rightMax arrays
leftMax[0] = 0;
rightMax[n - 1] = n - 1;
// Fill leftMax and rightMax arrays
for ( int i = 1; i < n; i++)
{
leftMax[i] = (arr[i] > arr[leftMax[i - 1]]) ? i : leftMax[i - 1];
}
for ( int i = n - 2; i >= 0; i--)
{
rightMax[i] = (arr[i] > arr[rightMax[i + 1]]) ? i : rightMax[i + 1];
}
// Traverse array to find maximum j and sum
int maxSum = int .MinValue;
for ( int j = 1; j < n - 1; j++)
{
int currSum = P * arr[leftMax[j - 1]] + Q * arr[j] + R * arr[rightMax[j + 1]];
if (currSum > maxSum)
{
maxSum = currSum;
indices[0] = leftMax[j - 1];
indices[1] = j;
indices[2] = rightMax[j + 1];
}
}
return indices;
}
static void Main()
{
int [] arr = { 1, 2, 3, 4, 5 };
int P = 1, Q = 2, R = 3;
int n = arr.Length;
int [] result = FindMaxWeightedTriplets(arr, P, Q, R, n);
Console.WriteLine($ "{result[0]} {result[1]} {result[2]}" );
Console.ReadLine();
}
} //this code is contributed by Adarsh |
// JavaScript Implementation function findMaxWeightedTriplets(arr, P, Q, R) {
let indices = [0, 0, 0];
let leftMax = new Array(arr.length);
let rightMax = new Array(arr.length);
// Initialize leftMax and rightMax arrays
leftMax[0] = 0;
rightMax[arr.length - 1] = arr.length - 1;
// Fill leftMax and rightMax arrays
for (let i = 1; i < arr.length; i++) {
leftMax[i] = arr[i] > arr[leftMax[i - 1]] ? i : leftMax[i - 1];
}
for (let i = arr.length - 2; i >= 0; i--) {
rightMax[i] = arr[i] > arr[rightMax[i + 1]] ? i : rightMax[i + 1];
}
// Traverse array to find maximum j and sum
let maxSum = Number.MIN_SAFE_INTEGER;
for (let j = 1; j < arr.length - 1; j++) {
let currSum = P * arr[leftMax[j - 1]] + Q * arr[j] + R * arr[rightMax[j + 1]];
if (currSum > maxSum) {
maxSum = currSum;
indices[0] = leftMax[j - 1];
indices[1] = j;
indices[2] = rightMax[j + 1];
}
}
return indices;
} let arr = [1, 2, 3, 4, 5]; let P = 1, Q = 2, R = 3; let result = findMaxWeightedTriplets(arr, P, Q, R); console.log(result[0], result[1], result[2]); // This code is contributed by Tapesh(tapeshdu420) |
2 3 4
Time Complexity: O(N), where N is the size of input array arr[].
Auxiliary Space: O(N)