Skip to content
LEETFLIX

Number of Ways to Buy Pens and Pencils

MediumMath
Solve on LeetCode

Medium · linear scan solution for Number of Ways to Buy Pens and Pencils. Python, Go, and a step-by-step animation.

01

Problem

Read the prompt, flip through the examples, then steal the idea.

LeetCode 2240. Number of Ways to Buy Pens and Pencils. The copyrighted prompt is on LeetCode. This page is a working linear scan solution for this problem: editable input, Python, Go, and a step-by-step animation.

Constraints

  • —Player inputs are capped so the animation stays readable.
  • —Match LeetCode's own constraints when you submit there.

Examples

Input

nums =
[2, 1, 5, 3]

Output

5

A single pass keeps the running maximum. 5 wins.

02

Solution

Python and Go. The walkthrough below runs this same code.

Approach 1Optimal▶ Animated

Number of Ways to Buy Pens and Pencils — linear scan

Keep a running answer while you walk the array once. Built for LeetCode 2240. Number of Ways to Buy Pens and Pencils.

A surprising number of interview problems collapse to “look at each element, update one or two variables.” Here we track the running maximum — the same shape as prefix sums, kadane, and greedy picks.

Algorithm

  1. Seed best with the first element.
  2. For each later x, set best = max(best, x).
  3. Return best.
Time
O(n)
Space
O(1)
Solution.py
class Solution:    def numberOfWaysToBuyPensAndPencils(self, nums: list[int]) -> int:        best = nums[0]        for x in nums[1:]:            if x > best:                best = x        return best
Watch this run

03

Interactive walkthrough

Playing “Number of Ways to Buy Pens and Pencils — linear scan”. Edit the input, hit Run, then scrub.

Approach: Number of Ways to Buy Pens and Pencils — linear scan

Loading animation…