Maximum Edges in a Triangle-Free Graph
Company: Virtu
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: hard
Interview Round: Onsite
You are given `n` labeled vertices arranged as a polygon. You may draw any undirected edge between two distinct vertices, including polygon sides and diagonals. The drawing may contain crossings; only graph adjacency matters.
Implement:
```text
max_triangle_free_edges(n: int) -> int
```
Return the largest number of edges a simple graph on these `n` vertices can have while containing no three vertices that are pairwise connected.
### Constraints
- `1 <= n <= 100_000_000`
- No self-loops or duplicate edges are allowed.
- The result must be computed without constructing the graph.
### Clarifications
- A triangle is a set of three distinct vertices with all three connecting edges present.
- Edge crossings do not create vertices and do not affect whether a triangle exists.
- Compute the answer as `floor(n / 2) * ceil(n / 2)`, not as `n * n / 4`. Under the stated bound, that product is at most `2_500_000_000_000_000`, so it is an exact integer in JavaScript `Number` as well as Java and C++ 64-bit integer types.
```hint Split the vertices
Consider how many cross-group edges are possible when every edge joins two different groups.
```
### Examples
```text
Input: n = 4
Output: 4
Input: n = 5
Output: 6
```
### Evaluation Focus
- Derive the extremal edge count for both even and odd `n`.
- Explain why the construction is triangle-free and why no denser graph can be triangle-free.
- Use constant extra space and constant-time arithmetic without an overflowing or inexact intermediate.
### Extension
Describe one graph construction that achieves the returned maximum.
Overview: Find the maximum number of edges possible in a triangle-free graph on n vertices. Practice extremal graph reasoning, a tight bipartite construction, and constant-time implementation.
Read the full Virtu Data Scientist interview experience this question came from
Given n labeled vertices arranged as a polygon, return the largest number of undirected edges in a simple graph on those vertices that contains no triangle. Polygon sides and diagonals are both allowed, crossings do not create vertices, and only graph adjacency determines whether a triangle exists.
Constraints
- 1 <= n <= 100_000_000.
- The graph is simple: no self-loops and no duplicate edges.
- Edge crossings do not affect adjacency and do not create vertices.
- Return the exact maximum without constructing the graph.
- Compute floor(n / 2) * ceil(n / 2) from the two integer halves rather than evaluating n * n / 4 through an inexact or overflowing intermediate; the maximum result is 2_500_000_000_000_000.
Examples
Input: (1,)
Expected Output: 0
Explanation: A single vertex has no possible edge.
Input: (2,)
Expected Output: 1
Explanation: The only possible edge cannot form a triangle.
Hints
- Consider how many cross-group edges are possible when every edge joins two different groups.