题目
题目链接
解题思路
这是一道可以多次买卖股票的问题,关键是要理解:
- 可以在同一天卖出后再买入
- 只要后一天价格比前一天高,就可以获得这个差价的利润
- 最终的最大利润就是所有上涨天数的差价之和
因此我们可以:
- 遍历价格数组
- 如果当天价格比前一天高,就把差价加到总利润中
- 这样就能获得最大收益
代码
#include <iostream>
#include <vector>
using namespace std;int maxProfit(vector<int>& prices) {int totalProfit = 0;for(int i = 1; i < prices.size(); i++) {if(prices[i] > prices[i-1]) {totalProfit += prices[i] - prices[i-1];}}return totalProfit;
}int main() {int n;cin >> n;vector<int> prices(n);for(int i = 0; i < n; i++) {cin >> prices[i];}cout << maxProfit(prices) << endl;return 0;
}
import java.util.Scanner;public class Main {public static int maxProfit(int[] prices) {int totalProfit = 0;for(int i = 1; i < prices.length; i++) {if(prices[i] > prices[i-1]) {totalProfit += prices[i] - prices[i-1];}}return totalProfit;}public static void main(String[] args) {Scanner sc = new Scanner(System.in);int n = sc.nextInt();int[] prices = new int[n];for(int i = 0; i < n; i++) {prices[i] = sc.nextInt();}System.out.println(maxProfit(prices));sc.close();}
}
def max_profit(prices):total_profit = 0for i in range(1, len(prices)):if prices[i] > prices[i-1]:total_profit += prices[i] - prices[i-1]return total_profitn = int(input())
prices = list(map(int, input().split()))
print(max_profit(prices))
算法及复杂度
- 算法:贪心算法
- 时间复杂度:\(\mathcal{O}(n)\),只需要遍历一次数组
- 空间复杂度:\(\mathcal{O}(1)\),只使用了常数个变量