



Your problem is very easy to solve, it fits well a first-lesson programming introduction course. The reason you wasted 2 days, is because you try to do it like R, while this problem is best solved in C. 




In fact, I think this problem demonstrated why R still maintain all the C features like for/if/while -- because there are problems that should not be solved in matrix thinking.




You want to know the "sales volme" in relation to the "minimum profit of each hand of deals". Here is the code and here is the result in two columnes





> get_volume_by_minimum_profit_rate_per_hand_of_deal <- function(A, B, profit) {

+     i = 1

+     j = 1

+     while (A[1,i] / B[1,j] > profit + 1) {

+         # step by step find the suitable volume

+         if (sum(A[2, 1:i]) > sum(B[2, 1:j])) { 

+             j = j + 1

+         } else {

+             i = i + 1

+         }

+     }

+     min(sum(A[2, 1:i]), sum(B[2, 1:j]))

+ }

> 


> for (i in seq(0.01, 0.023, 0.001)) {

+ print(c(paste(i*100, "%"), get_volume_by_minimum_profit_rate_per_hand_of_deal(to_sell_to, to_buy_from, i)))

+ }

[1] "1 %"   "20580"

[1] "1.1 %" "18445"

[1] "1.2 %" "15032"

[1] "1.3 %" "11032"

[1] "1.4 %" "10766"

[1] "1.5 %" "10434"

[1] "1.6 %" "10268"

[1] "1.7 %" "10102"

[1] "1.8 %" "6867" 

[1] "1.9 %" "3299" 

[1] "2 %" "717"

[1] "2.1 %" "551"  

[1] "2.2 %" "551"  

[1] "2.3 %" "219"  



See how this corrects your calculation? You calculated that "if the king requires minimum profit of 2%, the volume (total quantity) of goods being dealt should be a bit more than 1000", but look at your data, that means you dealet five hands to buy, and one hand to sell -- the 5th hand you buy is at the price of 61.9450, the one hand you sell is at the price of 63.170


(63.17/61.945 - 1) = 19.776%


so the last hand you buy doesn't quanlify minimum requirement. My calculation is right, with the minimum requirement of 2% profit, the volume you can deal is only 717.






	[[alternative HTML version deleted]]

