1. Day-by-Day Simulation
Intuition
Simulate each day chronologically from 1 to S. Keep food in hand, buying up to N whenever current food is insufficient.
Algorithm
- Step 1: If M > N or (S >= 7 and 6 * N < 7 * M), return -1.
- Step 2: Initialize foodInHand = 0, buyDays = 0.
- Step 3: For day 1 to S: if foodInHand < M: if day % 7 == 0 return -1 (closed!); else buyDays++, foodInHand += N.
- Step 4: Consume M: foodInHand -= M.
- Step 5: Return buyDays.
#include <iostream> using namespace std; class Solution {public: int minimumDays(int S, int N, int M) { if (M > N || (S >= 7 && 6 * N < 7 * M)) return -1; int foodInHand = 0; int buyDays = 0; for (int day = 1; day <= S; ++day) { if (foodInHand < M) { if (day % 7 == 0) return -1; // Sunday: closed buyDays++; foodInHand += N; } foodInHand -= M; } return buyDays; }}; int main() { Solution sol; cout << "S=10, N=16, M=2: " << sol.minimumDays(10, 16, 2) << endl; cout << "S=10, N=2, M=2: " << sol.minimumDays(10, 2, 2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(S) - Space complexity:
O(1)