标签:计算 输入 pre 买卖 时间复杂度 数组 div bsp code
1 int maxProfit(int* prices, int pricesSize) 2 { 3 if (pricesSize == 0 || pricesSize == 1) 4 return 0; 5 int i, j; 6 int sum = 0; 7 8 for (i = 0; i < pricesSize-1; i++) 9 { 10 for (j = i + 1; j < pricesSize; j++) 11 { 12 sum = (sum > (prices[j] - prices[i]) ? sum : (prices[j] - prices[i])); 13 } 14 } 15 16 return sum; 17 }
DP:时间复杂度O(N)
一遍遍历,边遍历边找最小值,边进行求最大,利润去掉内层循环,只需关注最低的股票价格。
1 int maxProfit(int* prices, int pricesSize) 2 { 3 if (pricesSize < 2) 4 return 0; 5 6 int sum = 0; 7 int minVal = prices[0]; 8 9 for (int i = 1; i < pricesSize; i++) 10 { 11 sum = (sum > (prices[i] - minVal) ? sum : (prices[i] - minVal)); 12 minVal = (minVal < prices[i] ? minVal : prices[i]); 13 } 14 15 return sum; 16 }
标签:计算 输入 pre 买卖 时间复杂度 数组 div bsp code
原文地址:https://www.cnblogs.com/ZhengLijie/p/12564773.html