使用C++重新排列陣列以最大化i*arr[i]
在本文中,我們將討論重新排列給定n個數字陣列的問題。基本上,我們必須從陣列中選擇元素。對於每個選擇的元素,我們會獲得一些分數,這些分數將通過當前元素的值 * 之前選擇的元素數量來計算。您應該選擇元素以獲得最高分。例如:
Input : arr[ ] = { 3, 1, 5, 6, 3 }
If we select the elements in the way it is given, our points will be
= 3 * 0 + 1 * 1 + 5 * 2 + 6 * 3 + 3 * 4
= 41
To maximize the points we have to select the elements in order { 1, 3, 3, 5, 6 }
= 1 * 0 + 3 * 1 + 3 * 2 + 5 * 3 + 6 * 4
= 48(maximum)
Output : 48
Input : arr[ ] = { 2, 4, 7, 1, 8 }
Output : 63尋找解決方案的方法
觀察示例,我們發現要獲得最高分,我們需要從小到大選擇元素。尋找解決方案的方法是:
- 將給定陣列按升序排序。
- 從索引0開始選擇元素到結尾。
- 計算選擇每個元素獲得的分數。
示例
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main () {
int arr[] = { 2, 4, 7, 1, 8 };
int n = sizeof (arr) / sizeof (arr[0]);
// sorting the array
sort (arr, arr + n);
int points = 0;
// traverse the array and calculate the points
for (int i = 0; i < n; i++) {
points += arr[i] * i;
}
cout << "Maximum points: " << points;
return 0;
}輸出
Maximum points: 63
上述程式碼的解釋
這段C++程式碼易於理解。首先我們對陣列進行排序,然後使用for迴圈遍歷陣列,計算從頭到尾選擇每個元素獲得的分數。
結論
在本文中,我們討論了從陣列中選擇元素以獲得最高分的問題,其中分數透過i * arr[i]計算。我們採用貪心演算法來解決這個問題並獲得最高分。還討論了C++程式碼來實現相同的目的,我們也可以用其他語言(如C、Java、Python等)編寫此程式碼。希望本文對您有所幫助。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP