2023-10-06 Daily Challenge

Today I have done leetcode's October LeetCoding Challenge with cpp.

October LeetCoding Challenge 6

Description

Integer Break

Given an integer n, break it into the sum of k positive integers, where k >= 2, and maximize the product of those integers.

Return the maximum product you can get.

 

Example 1:

Input: n = 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.

Example 2:

Input: n = 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.

 

Constraints:

  • 2 <= n <= 58

Solution

class Solution {
public:
  int integerBreak(int n) {
    int answer = 0;
    int k = 1;
    do {
      k += 1;
      int result = 1;
      int base = n / k;
      int reminder = n % k;
      for(int i = 0; i < n % k; ++i) {
        result *= base + 1;
      }
      for(int i = 0; i < k - n % k; ++i) {
        result *= base;
      }
      answer = max(result, answer);
    }while(k < n);
    return answer;
  }
};

// Accepted
// 50/50 cases passed (2 ms)
// Your runtime beats 49.96 % of cpp submissions
// Your memory usage beats 36.38 % of cpp submissions (6.3 MB)