✅ 0ms Beat 100% | ✨ TC O(1) SC O(1) | 🏆 Most Efficient | 👍 Simplest Intuitive Solution
Intuition\n Describe your first thoughts on how to solve this problem. \nThere is only one way to format a standard form mm:ss for a given time duration (the ta
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere is only one way to format a **standard form** $$mm:ss$$ for a given time duration (the `targetSeconds`), when we specify that $$ss$$ is less than 60.\n\nThere might be an **alternative form** when $ss$ of the standard form is less than 40. That is by converting 1 minute to 60 seconds.\n\nWe just need to try both forms and find the smallest cost.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$\\Theta(1)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$\\Theta(1)$$\n\n# Code\n```\nconstexpr int kFactors[] = {600, 60, 10, 1};\n\nclass Solution {\npublic:\n  int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {\n    start_at_ = startAt + \'0\';\n    move_cost_ = moveCost;\n    push_cost_ = pushCost;\n\n    // Find the standard form first.\n    string sequence = "0000";\n    for (int i = 0; i < 4; ++i) {\n      auto r = std::div(targetSeconds, kFactors[i]);\n      sequence[i] = r.quot + \'0\';\n      targetSeconds = r.rem;\n    }\n    int cost = 10\'000\'000;\n    // Large `targetSeconds` generates bad stardard form,\n    // for example 6540 => [10 9 0 0]\n    // In that case only the alternative form below applies.\n    if (sequence[0] <= \'9\') {\n      cost = CostOf(sequence);\n    }\n\n    // Now we try to use the alternative form.\n    if (sequence[2] <= \'3\') {\n      sequence[2] += 6;\n      if (--sequence[1] < \'0\') {  // handles carry\n        sequence[1] += 10;\n        --sequence[0];\n      }\n      if (sequence[0] >= \'0\') {  // Validates the form after carry.\n        cost = min(cost, CostOf(sequence));\n      }\n    }\n    return cost;\n  }\n\n  int CostOf(string_view sequence) const {\n    int cost = 0;\n    char d = start_at_;\n    for (char c : sequence) {\n      if (c == \'0\' && cost == 0) {\n        // Ignores leading 0s\n        continue;\n      }\n      cost += push_cost_ + (d == c ? 0 : move_cost_);\n      d = c;\n    }\n    // cout << "cost of [" << sequence << "] = " << cost << endl;\n    return cost;\n  }\n\n private:\n  char start_at_;\n  int move_cost_;\n  int push_cost_;\n};\n```
['C++']