M
myselfvinay
Guest
Given an array of positive integers of size n. A triplet(i,j,k) is said to be amazing if these two condition hold: 1. i<j<k 2. Ai < Aj, Ak Value of an amazing triplet(i,j,k)=Ai+(Aj*Ak) Find the maximum value among all possible values of amazing triplets. if there are no amazing triplets then print -1. Input: a[] = 13 16 2 7 3 18 19 6 15 11 17 Output: 358
I have written the program, it is working fine, but here i need help to optimize it for the performance, i have used multiple for loops, Need guidance to optimize the code.
// C# program to find maximum triplet sum using System;
using System;
using System.Text;
using System.Threading.Tasks;
class GFG
{
static int maxTripletSum(int[] arr, int n)
{
int ans = 0;
StringBuilder sb = new StringBuilder();
int prev = 0;
for (int i = 1; i < n - 1; ++i)
{
int max1 = 0, max2 = 0;
for (int j = 0; j < i; ++j)
if (arr[j] < arr)
max1 = Math.Max(max1, arr[j]);
for (int j = i + 1; j < n; ++j)
if (arr[j] > arr)
max2 = Math.Max(max2, arr[j]);
ans = max1 + (arr * max2);
if (prev > ans)
{
ans = prev;
}
else
{
prev = max1 + (arr * max2);
}
}
return ans;
}
public static void Main()
{
int[] arr = { 13, 16, 2, 7, 3, 18, 19, 6, 15, 11, 17 };
int n = arr.Length;
Console.WriteLine(maxTripletSum(arr, n));
Console.ReadLine();
}
}
Continue reading...
I have written the program, it is working fine, but here i need help to optimize it for the performance, i have used multiple for loops, Need guidance to optimize the code.
// C# program to find maximum triplet sum using System;
using System;
using System.Text;
using System.Threading.Tasks;
class GFG
{
static int maxTripletSum(int[] arr, int n)
{
int ans = 0;
StringBuilder sb = new StringBuilder();
int prev = 0;
for (int i = 1; i < n - 1; ++i)
{
int max1 = 0, max2 = 0;
for (int j = 0; j < i; ++j)
if (arr[j] < arr)
max1 = Math.Max(max1, arr[j]);
for (int j = i + 1; j < n; ++j)
if (arr[j] > arr)
max2 = Math.Max(max2, arr[j]);
ans = max1 + (arr * max2);
if (prev > ans)
{
ans = prev;
}
else
{
prev = max1 + (arr * max2);
}
}
return ans;
}
public static void Main()
{
int[] arr = { 13, 16, 2, 7, 3, 18, 19, 6, 15, 11, 17 };
int n = arr.Length;
Console.WriteLine(maxTripletSum(arr, n));
Console.ReadLine();
}
}
Continue reading...