Imagine you're a professional athlete preparing for the most important competition of your career! 🏃♂️💪
A futuristic sports scientist has provided you with two different energy drinks A and B, each offering varying energy boosts throughout the day. You have n hours to prepare, and you must drink exactly one energy drink per hour to maximize your total energy boost.
Here's the catch: switching between drinks isn't instant! If you want to switch from one energy drink to another, your body needs one full hour to cleanse your system - meaning you get zero energy boost during that transition hour.
Your Goal: Determine the maximum total energy boost you can achieve over n hours. You can start with either drink A or drink B.
Input: Two integer arrays energyDrinkA and energyDrinkB of length n, representing energy boosts per hour.
💡 Note:Start with B (3), switch to A in hour 2 but get 0 due to switching penalty, then get A (1) in hour 3. Total: 3 + 0 + 1 = 4. Or start with B (3), continue with B (1), continue with B (1). Total: 3 + 1 + 1 = 5. The maximum is 5.
The optimal solution uses dynamic programming to track the maximum energy possible ending with each drink type. At each hour, we calculate the maximum energy by either continuing with the same drink (no penalty) or switching drinks (with one-hour penalty). The key insight is that we only need to maintain two values: maximum energy ending with drink A and maximum energy ending with drink B. This gives us O(n) time and O(1) space complexity.
Common Approaches
✓
Hash Map
⏱️ Time: N/A
Space: N/A
Brute Force (Recursive Exploration)
⏱️ Time: O(2^n)
Space: O(n)
Generate all possible sequences of drink choices, considering the switching penalty. For each hour, try both drinks and recursively calculate the maximum energy from remaining hours.
Dynamic Programming (Optimal)
⏱️ Time: O(n)
Space: O(1)
Use dynamic programming to efficiently compute the maximum energy boost. At each hour, maintain the maximum energy possible ending with drink A and ending with drink B, considering the switching penalty.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 100003
typedef struct Node {
char key[32];
long long value;
struct Node *next;
} Node;
Node *hashTable[TABLE_SIZE];
unsigned int hash(const char *key) {
unsigned int h = 5381;
while (*key)
h = ((h << 5) + h) + (unsigned char)(*key++);
return h % TABLE_SIZE;
}
void memoSet(const char *key, long long value) {
unsigned int idx = hash(key);
Node *cur = hashTable[idx];
while (cur) {
if (strcmp(cur->key, key) == 0) { cur->value = value; return; }
cur = cur->next;
}
Node *node = (Node *)malloc(sizeof(Node));
strncpy(node->key, key, sizeof(node->key) - 1);
node->key[sizeof(node->key) - 1] = '\0';
node->value = value;
node->next = hashTable[idx];
hashTable[idx] = node;
}
int memoGet(const char *key, long long *out) {
unsigned int idx = hash(key);
Node *cur = hashTable[idx];
while (cur) {
if (strcmp(cur->key, key) == 0) { *out = cur->value; return 1; }
cur = cur->next;
}
return 0;
}
void memoClear() {
for (int i = 0; i < TABLE_SIZE; i++) {
Node *cur = hashTable[i];
while (cur) { Node *tmp = cur; cur = cur->next; free(tmp); }
hashTable[i] = NULL;
}
}
int *drinkA;
int *drinkB;
int n;
long long dp(int hour, int lastDrink) {
if (hour >= n) return 0;
char key[32];
snprintf(key, sizeof(key), "%d,%d", hour, lastDrink);
long long cached;
if (memoGet(key, &cached)) return cached;
long long result = 0, a, b;
if (lastDrink == -1) {
a = drinkA[hour] + dp(hour + 1, 0);
b = drinkB[hour] + dp(hour + 1, 1);
result = a > b ? a : b;
} else if (lastDrink == 0) {
a = drinkA[hour] + dp(hour + 1, 0);
b = dp(hour + 1, 1);
result = a > b ? a : b;
} else {
a = dp(hour + 1, 0);
b = drinkB[hour] + dp(hour + 1, 1);
result = a > b ? a : b;
}
memoSet(key, result);
return result;
}
long long solution(int *energyDrinkA, int *energyDrinkB, int size) {
drinkA = energyDrinkA;
drinkB = energyDrinkB;
n = size;
memoClear();
if (n == 0) return 0;
if (n == 1) return energyDrinkA[0] > energyDrinkB[0]
? energyDrinkA[0] : energyDrinkB[0];
return dp(0, -1);
}
int parseArray(const char *line, int *arr) {
const char *p = line;
while (*p && *p != '[') p++;
if (*p == '[') p++;
int count = 0;
while (*p && *p != ']') {
while (*p == ' ') p++;
if (*p == ']' || *p == '\0') break;
arr[count++] = (int)strtol(p, (char **)&p, 10);
while (*p == ',' || *p == ' ') p++;
}
return count;
}
int main(void) {
char lineA[1 << 20];
char lineB[1 << 20];
if (!fgets(lineA, sizeof(lineA), stdin)) return 1;
if (!fgets(lineB, sizeof(lineB), stdin)) return 1;
lineA[strcspn(lineA, "\n")] = '\0';
lineB[strcspn(lineB, "\n")] = '\0';
int *energyDrinkA = (int *)malloc((1 << 16) * sizeof(int));
int *energyDrinkB = (int *)malloc((1 << 16) * sizeof(int));
int sizeA = parseArray(lineA, energyDrinkA);
int sizeB = parseArray(lineB, energyDrinkB);
int size = sizeA < sizeB ? sizeA : sizeB;
printf("%lld\n", solution(energyDrinkA, energyDrinkB, size));
free(energyDrinkA);
free(energyDrinkB);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
23.5K Views
HighFrequency
~18 minAvg. Time
847 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.