Getting the x-coordinate of the global maximum on TGraph

How can one most easily obtain the x-coordinate of the global maximum (largest y-value) on a TGraph?

I’ve tried following the guidance here, however this doesn’t seem to accomplish what I’m after: TGraph GetMaximum() GetMinimum() - ROOT - ROOT Forum (cern.ch)

Scanning the TGraph documentation, there doesn’t seem to be anything that would be of use here. Unfortunately, the data are stored as TGraphs, so I need to extract this from the graphs.


Please read tips for efficient and successful posting and posting code

ROOT Version: Not Provided
Platform: Not Provided
Compiler: Not Provided


void maxelement()
{
   auto g = new TGraph();
   g->AddPoint(1,3);
   g->AddPoint(2,6);
   g->AddPoint(3,4);
   g->AddPoint(5,7);
   g->AddPoint(9,1);
   auto y = g->GetY();
   auto x = g->GetX();
   int n  = g->GetN();
   int i  = std::max_element(y,y+n)-y;
   cout << "X value of g maximum = " << x[i] << endl;
}

gives:

root [0] .x maxelement.C
X value of g maximum = 5