当前位置: 代码迷 >> 综合 >> 121-简单-买卖股票的最佳时机
  详细解决方案

121-简单-买卖股票的最佳时机

热度:52   发布时间:2024-03-10 01:03:52.0

在这里插入图片描述
1暴力求解

int maxProfit(int* prices, int pricesSize) {
    int temp1 = 0;int temp2 = 0;for (int i = 0; i < pricesSize - 1; i++) {
    for (int j = i+1; j < pricesSize; j++) {
    if (prices[j] <= prices[i]){
    continue;}temp2 = prices[j] - prices[i];if (temp1 < temp2){
    temp1 = temp2;}}}return temp1;
}

2动态规划

int maxProfit(int* prices, int pricesSize) {
    int profit = 0;int minprices = 0;int temp;if ((prices == NULL) || (pricesSize <=0 )) {
    return 0;}minprices = prices[0];for (int i = 0; i < pricesSize; i++) {
    if (prices[i] < minprices) {
    minprices = prices[i];continue;} temp = prices[i] - minprices;if (profit < temp) {
    profit = temp;}}return profit;
}
  相关解决方案