question

vinayKumar-2548 avatar image
0 Votes"
vinayKumar-2548 asked ·

Optimize the Program to generate the sum of the triplets

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;

class GFG {

 // Function to calculate maximum triplet sum 
 static int maxTripletSum(int[] arr, int n) 
 { 
        
     // Initialize the answer 
     int ans = 0; 

     for (int i = 1; i < n - 1; ++i) 
     { 
         int max1 = 0, max2 = 0; 

         // find maximum value(less than 
         // arr[i]) from i+1 to n-1 
         for (int j = 0; j < i; ++j) 
             if (arr[j] < arr[i]) 
                 max1 = Math.Max(max1, arr[j]); 

         // find maximum value(greater than 
         // arr[i]) from i+1 to n-1 
         for (int j = i + 1; j < n; ++j) 
             if (arr[j] > arr[i]) 
                 max2 = Math.Max(max2, arr[j]); 

         // store maximum answer 
     if(max1 && max2) 
         ans = Math.Max(ans, max1 + (arr[i] * max2)); 
     } 

     return ans; 
 } 

 // Driver code 
 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)); 
 } 

}








not-supported
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

DSPatrick avatar image
0 Votes"
DSPatrick answered ·

C# is not currently supported here on QnA. They're actively answering question in dedicated forums here.


https://social.msdn.microsoft.com/Forums/en-US/home?forum=csharpgeneral


--please don't forget to Accept as answer if the reply is helpful--


Regards, Dave Patrick ....
Microsoft Certified Professional
Microsoft MVP [Windows Server] Datacenter Management


Disclaimer: This posting is provided "AS IS" with no warranties or guarantees, and confers no rights.







· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.