买卖股票的最佳时机 II
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
解题思路:
贪心算法: 只关心当前最有解,总是做出在当前看来是最好的选择,不从整体上加以考虑
int maxProfit(int* prices, int pricesSize) {
int sum = 0, tmp = 0;
for (int i = 1; i < pricesSize; i++) {
tmp = prices[i] - prices[i-1];
if (tmp > 0)
sum += tmp;
}
return sum;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// int arr[] = {7,1,5,3,6,4};
// int arr[] = {7,6,4,3,1};
int arr[] = {1,2,3,4,5};
int sum = maxProfit1(arr, 5);
printf("%d\n",sum);
}
return 0;
}
我们要算的是利润,要有利润,自然要有一次交易。
所以我们就说说prices[1],即是第一天股票价格。按照贪心策略,不关心以后,我们只关心当前利益。第0天买入,花费prices[0],第一天卖出,得到prices[1],那么我们的收获就是profit = prices[1] - prices[0],那么有两种情况
(1)当profit > 0 时,赶紧买入卖出,能赚一笔是一笔,苍蝇再小也是肉嘛
(2)当profit <= 0 时,再买入卖出的话,那就是傻了,白费力气不说,还亏钱。
以此方式类推下去,即得最大利润。
参考文章:https://blog.csdn.net/newbie_lb/article/details/80007386
网友评论