You are given an integer eventTime denoting the duration of an event. You are also given two integer arrays startTime and endTime, each of length n. These represent the start and end times of n non-overlapping meetings that occur during the event between time t = 0 and time t = eventTime, where the ith meeting occurs during the time [startTime[i], endTime[i]].
You can reschedule at most one meeting by moving its start time while maintaining the same duration, such that the meetings remain non-overlapping, to maximize the longest continuous period of free time during the event.
Return the maximum amount of free time possible after rearranging the meetings.
Note: The meetings cannot be rescheduled to a time outside the event and they should remain non-overlapping. In this version, it is valid for the relative ordering of the meetings to change after rescheduling one meeting.
💡 Note:Initially gaps are [0,1]=1, [3,4]=1, [5,6]=1, [8,10]=2. By moving meeting [1,3] to [0,2], we get gaps [2,4]=2, [5,6]=1, [8,10]=2, with max gap = 2. By moving it to position [2,4], we merge gaps to get [0,1]=1, [5,6]=1, [8,10]=2. But moving [6,8] to [2,4] gives gaps [0,1]=1, [4,6]=2, [8,10]=2. Actually, moving [1,3] completely out creates a gap [0,1]+[3,4] and placing it at end gives [0,4]=4.
💡 Note:With one meeting [3,7], current max gap is max(3, 3) = 3. Moving it to [0,4] gives gap [4,10]=6. Moving it to [6,10] gives gap [0,6]=6. Moving to [3,7] gives original max gap 3. Best is moving to start: gap = 7.
Reschedule Meetings for Maximum Free Time II — Solution
The key insight is to systematically try rescheduling each meeting to strategic positions that can create or extend free time gaps. The greedy approach works by identifying current gaps and placing meetings at positions that maximize continuous free time. Time: O(n² × log n), Space: O(n)
Common Approaches
✓
Brute Force - Try All Positions
⏱️ Time: O(n² × eventTime)
Space: O(n)
For each meeting, try placing it at every possible valid position in the timeline. After each placement, calculate the maximum continuous free time and keep track of the best result.
Greedy - Smart Gap Optimization
⏱️ Time: O(n² × log n)
Space: O(n)
First find all current free time gaps, then for each meeting, determine the best position that creates maximum continuous free time by either extending existing gaps or creating new optimal gaps.
Brute Force - Try All Positions — Algorithm Steps
Step 1: For each meeting, try removing it and placing it at every valid position
Step 2: For each placement, check if it creates overlaps with other meetings
Step 3: Calculate maximum continuous free time for valid placements
Step 4: Return the maximum free time found across all attempts
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Select Meeting
Choose a meeting to reschedule
2
Try Positions
Test every valid position for the meeting
3
Find Maximum
Calculate free time and keep the best result
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
int start, end;
} Meeting;
int compare(const void *a, const void *b) {
Meeting *ma = (Meeting*)a;
Meeting *mb = (Meeting*)b;
return ma->start - mb->start;
}
int isValid(Meeting *meetings, int n) {
qsort(meetings, n, sizeof(Meeting), compare);
for (int i = 0; i < n - 1; i++) {
if (meetings[i].end > meetings[i + 1].start) {
return 0;
}
}
return 1;
}
int getMaxFreeTime(Meeting *meetings, int n, int eventTime) {
Meeting temp[n];
memcpy(temp, meetings, n * sizeof(Meeting));
qsort(temp, n, sizeof(Meeting), compare);
int maxGap = temp[0].start; // Gap before first meeting
for (int i = 0; i < n - 1; i++) {
int gap = temp[i + 1].start - temp[i].end;
if (gap > maxGap) maxGap = gap;
}
int lastGap = eventTime - temp[n - 1].end; // Gap after last meeting
if (lastGap > maxGap) maxGap = lastGap;
return maxGap;
}
int solution(int eventTime, int *startTime, int *endTime, int n) {
Meeting meetings[n];
for (int i = 0; i < n; i++) {
meetings[i].start = startTime[i];
meetings[i].end = endTime[i];
}
int maxFreeTime = getMaxFreeTime(meetings, n, eventTime);
// Try rescheduling each meeting
for (int i = 0; i < n; i++) {
int duration = endTime[i] - startTime[i];
// Try placing meeting i at every possible position
for (int newStart = 0; newStart <= eventTime - duration; newStart++) {
int newEnd = newStart + duration;
// Create new meeting list with meeting i moved
Meeting newMeetings[n];
int idx = 0;
for (int j = 0; j < n; j++) {
if (j != i) {
newMeetings[idx++] = meetings[j];
}
}
newMeetings[n-1].start = newStart;
newMeetings[n-1].end = newEnd;
if (isValid(newMeetings, n)) {
int freeTime = getMaxFreeTime(newMeetings, n, eventTime);
if (freeTime > maxFreeTime) maxFreeTime = freeTime;
}
}
}
return maxFreeTime;
}
void parseArray(const char* str, int* arr, int* size) {
*size = 0;
const char* p = str;
while (*p && *p != '[') p++;
if (*p == '[') p++;
while (*p && *p != ']') {
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
arr[(*size)++] = (int)strtol(p, (char**)&p, 10);
}
}
int main() {
int eventTime;
scanf("%d", &eventTime);
char line[1000];
scanf(" %s", line);
// Parse start times
int startTime[100], endTime[100], n = 0;
char *token = strtok(line + 1, ",]");
while (token != NULL) {
startTime[n++] = atoi(token);
token = strtok(NULL, ",]");
}
scanf(" %s", line);
// Parse end times
int idx = 0;
token = strtok(line + 1, ",]");
while (token != NULL) {
endTime[idx++] = atoi(token);
token = strtok(NULL, ",]");
}
int result = solution(eventTime, startTime, endTime, n);
printf("%d\n", result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n² × eventTime)
For each of n meetings, try eventTime positions, each taking O(n) time to validate
n
2n
⚠ Quadratic Growth
Space Complexity
O(n)
Store meeting information and temporary arrays for validation
n
2n
⚡ Linearithmic Space
2.5K Views
MediumFrequency
~25 minAvg. Time
89 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.