Clear and easy-to-understand Java solution with explanation


  • 2
    K
    public class Solution {
        public int integerBreak(int n) {
            if(n == 2) return 1;
            if(n == 3) return 2;
            if(n == 4) return 4;
            // 5   6   7  Group 1
            // 32  33  34
            // 8   9   10  Group 2
            // 332 333 334  
            // 11    12    13   Group 3
            // 3332  3333  3334
            int groupNumber = (n - 5)/3 + 1;
            int addition = n - 3 * (groupNumber);
            int res = 1;
            while(groupNumber != 0){
                res *= 3;
                groupNumber--;
            }
            return res * addition;
        }
    }

  • 0
    T
    var integerBreak = function(n) {
      var result = 1;
    
      if (n === 2) {
        return 1;
      }
    
      if (n === 3) {
        return 2;
      }
    
      if (n === 4) {
        return 4;
      }
      // 5, 8, 11 could see as one group so as 6, 9, 12
      // then the based case is just 5,6,7
      while (n > 7) {
        n -= 3;
        result *= 3;
      }
    
      switch (n) {
        case 5:
          return result * 2 * 3;
        case 6:
          return result * 3 * 3;
        case 7:
          return result * 3 * 4;
      }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.