Untitled

 avatar
unknown
plain_text
9 days ago
1.1 kB
2
Indexable
import java.util.HashMap;
import java.util.Map;

class Solution {
    public int maxSizeSlices(int[] slices) {
        int n = slices.length / 3;
        // Solve for two cases: excluding the first or last slice
        return Math.max(
            solve(slices, 0, slices.length - 2, n, new HashMap<>()), 
            solve(slices, 1, slices.length - 1, n, new HashMap<>())
        );
    }

    private int solve(int[] slices, int start, int end, int n, Map<String, Integer> memo) {
        if (n == 0) return 0; // No slices left to pick
        if (start > end) return 0; // No slices available in this range
        
        String key = start + "," + n;
        if (memo.containsKey(key)) {
            return memo.get(key);
        }

        // Two choices: skip the current slice or pick it
        int skip = solve(slices, start + 1, end, n, memo);
        int pick = slices[start] + solve(slices, start + 2, end, n - 1, memo);

        int result = Math.max(skip, pick);
        memo.put(key, result);
        return result;
    }
}
Editor is loading...
Leave a Comment