使最大尺寸的后序之和最小化,以便没有两个元素是相邻的

143 阅读2分钟

使最大尺寸的后序之和最小化,以便没有两个元素是相邻的

给定一个正数数组 arr[],任务是找到一个最大可能元素的子序列的最小和,约束条件是该序列中没有两个数字相邻。

例子。

输入: arr[]={1, 7, 3, 2}
输出。 3
解释。 选择子序列{1, 2}。
总和是3,没有两个元素是相邻的。
这是最不可能的和。

**输入:**arr[]={1, 8, 4, 10, 6}
**输出。**11
**解释。**选择子序列{1, 4, 6}。
总和是11,没有两个元素相邻。
这是最不可能的和。

**输入:**arr[]={2, 0, 11, 2, 0, 2}
**输出。**4
**解释。**选择子序列{0, 2, 2}。
和是4,没有两个元素相邻。
这是最不可能的和。

办法。 要解决这个问题,请遵循以下意见。

有两种不同的情况。

  • 阵列大小是奇数 - 唯一的选择是挑选偶数索引的元素(零基索引)。
  • 阵列大小是偶数- 子序列大小将是N/2。它可以有三种可能的方式
    • 所有偶数索引的元素。
    • 所有奇数索引的元素。
    • 直到i的偶数索引元素和从i+3开始的奇数索引元素
    • 这3个元素中的最小值将是答案。

请按照以下步骤来解决这个问题。

  • 如果arr[]的大小是奇数,所有偶数索引的元素之和就是答案。
  • 对于arr的大小为偶数, 将所有偶数索引的总和存入一个变量。
    • 从末尾开始迭代,增加奇数索引的元素,并从末尾删除偶数索引的元素。
    • 更新每个索引中的最小答案。
  • 迭代结束后,返回最小值作为答案。

下面是上述方法的实现。

C++

// C++ code for the above approach:

#include <bits/stdc++.h>
using namespace std;

// Function to find the minimum sum
int FindMinSum(vector<int>& vec, int n)
{
	int sum = 0;
	for (int i = 0; i < n; i += 2) {

		// Sum of all the even indices
		sum += vec[i];
	}
	if (n % 2 != 0)
		return sum;
	int ans = sum;
	for (int i = n - 1; i > 0; i -= 2) {

		// Removing the even index and
		// addinig the odd index
		sum = sum - vec[i - 1] + vec[i];

		// Checking for the minimum sum
		ans = min(sum, ans);
	}

	// Return the minimum sum
	return ans;
}

// Driver Code
int main()
{

	// Creating the array
	vector<int> arr = { 2, 0, 11, 2, 0, 2 };
	int N = vec.size();

	// Function call
	cout << FindMinSum(arr, N) << endl;

	return 0;
}

Python

# Python code to implement the approach
def FindMinSum(list, n):
	sum = 0
	for i in range(0, n, 2):
		# sum of all the odd indexes
		sum = sum + list[i]
	if n % 2 == 1:
		return sum
	ans = sum
	for i in range(n-1, 0, -2):
		# removing the odd index and addinig the even index
		sum = sum - list[i-1] + list[i]
		# checking for the minimum sum
		ans = min(sum, ans)
	# Return the minimum sum
	return ans


# Driver Code
# Creating the list
list = [2, 0, 11, 2, 0, 2]
n = 6
# Function call
k = FindMinSum(list, n)
print(k)

C#

// C# code for the above approach:
using System;

public class GFG {
static int solve(int[] vec, int n)
{
	int sum = 0;
	if (n % 2 != 0) {
	for (int i = 0; i < n; i = i + 2)
	{

		// sum of all the odd indexes
		sum = sum + vec[i];
	}
	return sum;
	}
	else {
	int ans = sum;
	for (int i = n - 1; i > 0; i -= 2)
	{

		// removing the odd index and addinig the
		// even index
		ans = ans - vec[i - 1] + vec[i];

		// checking for the minimum sum
		ans = Math.Min(ans, sum);
	}

	// Return the minimum sum
	return ans;
	}
}

// Driver Code
static public void Main()
{
	// Creating the array
	int[] vec = { 2, 1, 2 };

	int n = vec.Length;

	// Function call
	Console.WriteLine(solve(vec, n));
}
}

// This code is contributed by Rohit Pradhan

输出

4

时间复杂度。 O(N)
辅助空间。 O(1) \