Maximizing Points in a Paper Cut: An Engaging Problem Solved with PHP

Cleyton Bonamigo
2 min readJun 20, 2023

--

Today, we’re going to delve into an engaging problem that involves a unique strategy to maximize points. This problem showcases the beauty of dynamic programming and how it can be implemented using PHP to arrive at an optimal solution.

Problem Definition:

The problem involves a sequence of x’s and o’s written on a piece of paper. The goal is to cut this paper into two pieces such that the number of points we get is maximized. Points are computed by adding the number of x’s on the left half of the paper and the number of o’s on the right half of the paper. The task is to determine the maximum number of points we can get.

Consider the following examples:

Example1:
Input: s = “xoooxo”
Output: 5 (Cut the paper between the fourth and fifth characters. The left side has one ‘x’ and the right side has four ‘o’s.)

Example 2:
Input: s = “xxoo”
Output: 3 (Cut the paper between the second and third characters. The left side has two ‘x’s and the right side has one ‘o’.)

Example 3:
Input: s = “ooxxox”
Output: 4 (Cut the paper between the fourth and fifth characters. The left side has one ‘x’ and the right side has three ‘o’s.)

Algorithm:

The solution is a PHP function that uses a dynamic programming approach to solve the problem. Here’s how it looks:

function maxPoints($s) {
$len = strlen($s);
$countXLeft = $countORight = 0;

for ($i = $len - 1; $i >= 0; $i--) {
if ($s[$i] == 'o') {
$countORight++;
}
}

$maxPoints = $countORight;

for ($i = 0; $i < $len - 1; $i++) {
if ($s[$i] == 'x') {
$countXLeft++;
} else {
$countORight--;
}

$points = $countXLeft + $countORight;

if ($points > $maxPoints) {
$maxPoints = $points;
}
}

return $maxPoints;
}

echo maxPoints("xoooxo"); // Outputs: 5
echo maxPoints("xxoo"); // Outputs: 3
echo maxPoints("ooxxox"); // Outputs: 4

This solution first counts all the ‘o’s from right to left, then it iterates from left to right, calculating the points if a cut was made at that point and updating the maximum points accordingly.

Time and Space Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input string. This is because we perform a single pass over the string to calculate the points.

The space complexity is O(1) as we only use a few variables to store the counts and the maximum points, and this does not grow with the size of the input string.

You can check this code and others and test it in my GitHub Repository.

--

--

Cleyton Bonamigo

A Senior Software Engineer, writing code in PHP/Laravel and passionate about new technologies.