
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find number of operations needed to convert list into non-increasing list in Python
Suppose we have a list of numbers called nums. Now let us consider an operation where we take two consecutive values and merge it into one value by taking their sum. We have to find the minimum number of operations required so that the list turns into non−increasing.
So, if the input is like nums = [2, 6, 4, 10, 2], then the output will be 2, as we can merge [2, 6] to get [8, 4, 10, 2] and then merge [8, 4] to get [12, 10, 2].
To solve this, we will follow these steps −
if nums is empty, then
return 0
insert −inf at the end of nums
N := size of nums
dp := a list of size N and fill with 0
arr := a list of size N and fill with 0
p := size of arr
arr[p−1] := nums[N−1]
arr[p−2] := nums[N−2]
for i in range N − 3 to 0, decrease by 1, do
j := i
x := nums[j]
while j < N − 1 and x < arr[j + 1], do
j := j + 1
x := x + nums[j]
dp[i] := j − i + dp[j + 1]
arr[i] := x
return dp[0]
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): if not nums: return 0 nums.append(float("−inf")) N = len(nums) dp = [0] * N arr = [0] * N arr[−1] = nums[−1] arr[−2] = nums[−2] for i in range(N − 3, −1, −1): j = i x = nums[j] while j < N − 1 and x < arr[j + 1]: j += 1 x += nums[j] dp[i] = j − i + dp[j + 1] arr[i] = x return dp[0] ob = Solution() nums = [2, 6, 4, 10, 2] print(ob.solve(nums))
Input
[2, 6, 4, 10, 2]
Output
2
- Related Articles
- Python Program to convert a list into matrix with size of each row increasing by a number
- Python Program to Convert List into Array
- Python program to convert a list of tuples into Dictionary
- Convert list into list of lists in Python
- Convert list of tuples into list in Python
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Program to count number of operations required to convert all values into same in Python?
- Python program to convert a list into a list of lists using a step value
- Convert number to list of integers in Python
- Program to find number of operations needed to decrease n to 0 in C++
- Python - Convert given list into nested list
- Convert a string representation of list into list in Python
- Convert list of string to list of list in Python
- Convert list of tuples to list of list in Python
- Convert list of string into sorted list of integer in Python
