在C++中查詢三個棧可能相等的最大和
假設我們有三個正數棧。我們必須找到允許移除頂部元素的棧可能相等的最大的和。棧用陣列表示。陣列的第一個索引表示棧的頂部元素。假設棧元素類似於[3, 10]、[4, 5]和[2, 1]。輸出將為0。只有在從所有棧中移除所有元素後,和才能相等。
為了解決這個問題,我們將遵循這個思路。這個思路是比較每個棧的和,如果它們不相等,則移除具有最大和的棧的頂部元素。我們將遵循以下步驟:
查詢各個棧中所有元素的和。
如果三個棧的和相等,則這是最大和。
否則,移除三個棧中和最大的棧的頂部元素。然後重複步驟1和步驟2。
示例
#include <iostream>
#include <algorithm>
using namespace std;
int maxStackSum(int stk1[], int stk2[], int stk3[], int size1, int size2, int size3) {
int add1 = 0, add2 = 0, add3 = 0;
for (int i=0; i < size1; i++)
add1 += stk1[i];
for (int i=0; i < size2; i++)
add2 += stk2[i];
for (int i=0; i < size3; i++)
add3 += stk3[i];
int top1 =0, top2 = 0, top3 = 0;
int ans = 0;
while (true){
if (top1 == size1 || top2 == size2 || top3 == size3)
return 0;
if (add1 == add2 && add2 == add3)
return add1;
if (add1 >= add2 && add1 >= add3)
add1 -= stk1[top1++];
else if (add2 >= add3 && add2 >= add3)
add2 -= stk2[top2++];
else if (add3 >= add2 && add3 >= add1)
add3 -= stk3[top3++];
}
}
int main() {
int stack1[] = { 3, 2, 1, 1, 1 };
int stack2[] = { 4, 3, 2 };
int stack3[] = { 1, 1, 4, 1 };
int size1 = sizeof(stack1)/sizeof(stack1[0]);
int size2 = sizeof(stack2)/sizeof(stack2[0]);
int size3 = sizeof(stack3)/sizeof(stack3[0]);
cout << "The maximum sum is: " << maxStackSum(stack1, stack2, stack3, size1, size2, size3);
}輸出
The maximum sum is: 5
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP