348. Total Price Fluctuation
Total Price Fluctuation
A company records the daily price of a product in prices. The fluctuation during a contiguous, non-empty period is the difference between its highest and lowest prices.
Return the sum of the fluctuations for all possible periods.

Method Signature

long totalPriceFluctuation(List<Integer> prices)

Parameters

  • prices contains the product price recorded on each day.

Return Value

Return the sum of the price fluctuations across all contiguous, non-empty periods.

Constraints

  • 1 <= prices.size() <= 1,000
  • -1,000,000,000 <= prices.get(i) <= 1,000,000,000

Examples

Example 1

totalPriceFluctuation(prices = [4, 1, 3])
Output: 8
The three periods containing multiple prices have fluctuations 3, 2, and 3. All single-day periods have zero fluctuation.

Example 2

totalPriceFluctuation(prices = [2, 5, 2])
Output: 9
The periods [2, 5], [5, 2], and [2, 5, 2] each have a fluctuation of 3.

Example 3

totalPriceFluctuation(prices = [7, 7, 7])
Output: 0
Every period has the same highest and lowest price, so every fluctuation is zero.


Please use Laptop/Desktop or any other large screen to add/edit code.