สมมติว่าเรากำลังขาย 4 รายการและราคาของรายการ i-th อยู่ในอาร์เรย์ 'cost[i]' ตอนนี้เราขายสินค้าตามลำดับที่ระบุในสตริง 'items' เราต้องหาจำนวนยอดขายทั้งหมดที่เราทำ สตริง 'items' มีตัวเลขจำนวนเต็มตั้งแต่ 1 ถึง 4 สามารถสแกนซ้ำได้และจะเรียงลำดับอย่างไรก็ได้
ดังนั้น หากอินพุตเท่ากับ cost ={10, 15, 10, 5} รายการ ="14214331" ผลลัพธ์จะเป็น 75
ขั้นตอน
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนเหล่านี้ -
total := 0 for initialize i := 0, when i < size of items, update (increase i by 1), do: total := total + cost[items[i] - '0' - 1] return total
ตัวอย่าง
ให้เราดูการใช้งานต่อไปนี้เพื่อความเข้าใจที่ดีขึ้น
#include <bits/stdc++.h>
using namespace std;
#define N 100
int solve(int cost[], string items) {
int total = 0;
for(int i = 0; i < items.size(); i++)
total += cost[items[i] -'0' - 1];
return total;
}
int main() {
int cost[] = {10, 15, 10, 5};
string items = "14214331";
cout<< solve(cost, items);
return 0;
} อินพุต
{10, 15, 10, 5}, "14214331" ผลลัพธ์
75