[LeetCode Daily Question] [Simple] 122. The Best Time to Buy and Sell Stocks II

[LeetCode Daily Question] [Simple] 122. The Best Time to Buy and Sell Stocks II

122. The Best Time to Buy and Sell Stocks II

Source of topic
Algorithm idea: Array

topic:
Insert picture description here

java code

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
		int maxProfit = 0;
        int n = prices.length;
        for (int i = 1; i < n; i++) {
    
    
             // 一直向后遍历寻找,如果当前的值大于前一个的值,说明是一个盈利的点
            // 相当于从头开始,只要是上升就计算利润
        	if (prices[i] > prices[i-1]) {
    
    
				maxProfit += prices[i] - prices[i-1];
			}
		}
        return maxProfit;
    }
}

121. The best time to buy and sell stocks

Source of topic
Algorithm idea: Array

topic:
Insert picture description here

java code

class Solution {
    
    
    public int maxProfit(int[] prices) {
    
    
        //如果长度是0或者1,直接返回0
        if (prices.length == 0 || prices.length == 1) {
    
    
			return 0;
		}
		int min = prices[0];//记录最小值
		int income = 0;//记录可能的收入
		for (int i = 0; i < prices.length; i++) {
    
    
			int tmp = prices[i] - min;//计算当前可能获得的收入
			if (tmp > income) {
    
    //如果比之前的收入大,存起来
				income = tmp;
			}
			if (prices[i] < min) {
    
    //比较最小值,如果有新的,更新最小值
				min = prices[i];
			}
		}
		return income;//返回收入
    }
}

Guess you like

Origin blog.csdn.net/qq_39457586/article/details/109558906